views:

109

answers:

2

I have been trying to solve this problem the whole day:

How do I pass a double array to a function?

Here is an example:

int matrix[5][2] = { {1,2}, {3,4}, {5,6}, {7,8}, {9,10} };

And I wish to pass this matrix to function named eval_matrix,

void eval_matrix(int ?) {
    ...
}

I can't figure out what should be in place of ?

Can anyone help me with this problem?

I know that an array can be passed just as a pointer, but what about a double array (or triple array?)

Thanks, Boda Cydo.

+4  A: 

To be usable as an array the compiler has to know the inner stride of the array, so it's either:

void eval_matrix( int m[5][2] ) { ...

or:

void eval_matrix( int m[][2], size_t od ) { ... /* od is the outer dimension */

or just:

void eval_matrix( int* p, size_t od, size_t id ) { ... /* ditto */

In any case it's syntactic sugar - the array is decayed to a pointer.

In first two cases you can reference array elements as usual m[i][j], but will have to offset manually in the third case as p[i*id + j].

Nikolai N Fetissov
Thanks, I will use the 3rd possibility.
bodacydo
what about `int**`?
valya
What about `int**`? The question asked how to pass `int [][]` to a function. They are oh-so-different.
Nikolai N Fetissov
A: 

You should not pass the whole matrix, instead you should pass the pointer, however, you should pass the size too... this is how I would do it, assuming it is always pairs [2].

struct pair {
   int a, b;
};

struct pair matrix[] = { {1,2}, {3,4}, {5,6}, {7,8}, {9,10} };

void eval_matrix(struct pair *matrix, size_t matrix_size) {
  ...
}

eval_matrix(matrix, sizeof(matrix) / sizeof(struct pair);