Reputation: 79549
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.
Upvotes: 5
Views: 1580
Reputation: 3308
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);
Upvotes: -1
Reputation: 84239
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]
.
Upvotes: 6