5

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.

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • 1
    possible duplicate of http://stackoverflow.com/questions/2828648/how-to-pass-a-multidimensional-array-to-a-function-in-c-and-c – Jens Gustedt Jul 10 '10 at 21:20

2 Answers2

6

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 Fetissov
  • 82,306
  • 11
  • 110
  • 171
-1

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);
niry
  • 3,238
  • 22
  • 34