Method Call with Parameters of an Array

3

I've always created vector methods using:

void exemplo(int vetor[], int qtd){  
// Código...  
// ...  
}  

And I never had problems, but I'm trying the same with arrays and I get an error

void exemplo(int matriz[][], int lin, int col){  
// Código...  
// ...  
}

The error is:

  

array type has incomplete element type

Follow an image with the code

What's the problem?

    
asked by anonymous 18.09.2015 / 09:57

1 answer

2

In C arrays do not really exist. In the background they are pointers .

When you access a matriz[i] element you are actually doing *(matriz + i) .

In a multi-dimensional array matriz[i][j] is doing *(matriz + i * dimensao + j) . What is the value of dimensao there? There is no telling how you are using it. Multiplication is necessary to get the displacement. A dimension is a grouping of elements. To access them you need to know how many elements you have in one of the dimensions. The other is not necessary to know.

If you change the parameter to int matriz[][3] there you will be *(matriz + i * 3 + j) . You can specify the size of the two dimensions if you want: int matriz[3][3] .

An example:

#include<stdio.h>
void print(int matriz[][3], int lin, int col) {
    for(int i = 0; i < lin; i++) {
        for(int j = 0; j < col; j++) {
            printf("%d, ", matriz[i][j]);
        }
    }
}

int main() {
    int a[3][3] = {{0}};
    print(a, 3, 3);
}

See running on ideone .

One solution is to use pointer instead of array . Here you control access to the elements at hand:

#include<stdio.h>
#include <stdlib.h>
void print(int *matriz, int lin, int col) {
    for(int i = 0; i < lin; i++) {
        for(int j = 0; j < col; j++) {
            printf("%d, ", *(matriz + i * col + j));
        }
    }
}

int main() {
    int * a = malloc(9 * sizeof(int));
    print(a, 3, 3);
}

See working on ideone .

    
18.09.2015 / 12:44