Pass array as function parameter?

2

I am studying the Dijkstra algorithm and have not yet tried to use adjacency list. I knew I could solve the problem with an array, but the fact is that I can not get the array in the function. If I put the code direct in main it works as expected. This is the prototype I tried to use:

/*
 * v = grafo em forma de matriz
 * n = qtd de vértices
 * o = origem
 */
int * Dijkstra ( int v[][], int n, int o );
    
asked by anonymous 25.04.2015 / 03:37

1 answer

4

In C, you need to specify the size of all dimensions of an array that is a function argument, except for the leftmost dimension size. For example, if you define that your arrays will always be 100x100, you can define the type of your function like this:

int * Dijkstra ( int v[100][100], int n, int o );

or so:

int * Dijkstra ( int v[][100], int n, int o );

The reason for this comes from the way in which matrices of C are represented in memory. Lines are placed sequentially in a vector. For example, the 3x3 array

10 20 30
40 50 60
70 80 90

It is represented in memory as a vector of size 9

M[i][j] ->    10 20 30 40 50 60 70 80 90
i       ->     0  0  0  1  1  1  2  2  2
j       ->     1  2  3  1  2  3  1  2  3

When you access the (i,j) field of the 3x3 array, what C does under the wads is to access the 3*i + j field of the "vector". So the compiler has to know at compile time how many columns there are in each row, which is the factor that multiplies i .

If you do not want to set the dimensions of your array at compile time there are some alternatives you can do. The most common is to use a vector of vectors rather than a multidimensional vector. So your array has a type "integer pointer vector" int ** instead of the type "two-dimensional integer vector 100x100" int [100][100] .

 M ->  |*| --> [10 20 30]
       |*| --> [40 50 60]
       |*| --> [70 80 90]

An example of how to allocate an MxN array:

// Alocando a matriz dinâmicamente
int ** mat = malloc((sizeof int*) * M;
int  * buf = malloc((sizeof int) * M * N);
for(int i=0; i<M; i++){
    mat[i] = &buf[N*i];
}

// Usando a matriz:
for(int i=0; i<M; i++){
    for(int j=0; j<N; j++){
        mat[i][j] = f(i,j);
    }
 }

 // Libere a memória alocada dinamicamente quando você acabar de usar.
 free(mat);
 free(buf);
    
25.04.2015 / 03:58