abc - 1 year ago 85
C Question

2D array passing in C

How can I create an array so that I can pass it as a pointer to this function?

``````void SomeFunction(double *a, double *b, double *c);
``````

I made my 2d arrays like so (but I have errors):

``````static double matrix_a [MATRIX_DIM][MATRIX_DIM];
static double matrix_b [MATRIX_DIM][MATRIX_DIM];
static double matrix_c [MATRIX_DIM][MATRIX_DIM];

for (i=0;i<MATRIX_DIM;i++) {
for (j=0;j<MATRIX_DIM;j++) {
// initializing matrices here
}
}
``````

Now I make pointers to the arrays:

``````double *a = &matrix_a;
double *b = &matrix_b;
double *c = &matrix_c;
``````

And then call the function:

``````SomeFunction(a, b, c);
``````

However I get the following error:

``````cannons.c: In function ‘main’:
cannons.c:29:14: warning: initialization from incompatible pointer type      [enabled by default]
double *a = &matrix_a;
^
cannons.c:30:14: warning: initialization from incompatible pointer type [enabled by default]
double *b = &matrix_b;
^
cannons.c:31:14: warning: initialization from incompatible pointer type [enabled by default]
double *c = &matrix_c;
^
``````

Why ?

`double *` means "pointer to a single double". However you have an array whose elements are arrays of double. So you in fact want a pointer to an array of double:

``````double (*a)[MATRIX_DIM] = &matrix_a[0];   // or matrix_a
``````

when you access it as `a[1][2] = 5.0;`. Alternatively you could point to the entire array at once:

``````double (*x)[MATRIX_DIM][MATRIX_DIM] = &matrix_a;
``````

but then you need an extra level of indirection to access it: `(*x)[1][2] = 5.0;`

You will need to use the same declaration in the parameter list too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download