abc - 5 months ago 35

C Question

**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);`

`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

}

}

`double *a = &matrix_a;`

double *b = &matrix_b;

double *c = &matrix_c;

`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 ?

Answer

`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.