I have this loop which gives seg. fault.
s->c = malloc(width * height * sizeof(double));
if (s->c == NULL) { puts("malloc failed"); exit(1); }
for (int n = 0; n < width; n++) {
for (int m = 0; m < height; m++) {
d = (&s->c)[m][n];
printf("d %f\n", d);
printf("m %i\n", m);
printf("n %i\n", n);
}
}
Inside s->c is:
double* c;
When executed it just outputs:
d 27.000000
m 0
n 0
and then seg. fault.
It worked when I treated the s->c as a 1D array, but I would really like to treat it as a 2D array.
Is that possible, when the c pointer is in a struct?
If so, is (&s->c)[m][n]
then the correct way to access the elements?
Sandra
A common misconception is that an array and a pointer are completely interchangeable. An array name is not a pointer. Although an array name can be treated as a pointer at times, and array notation can be used with pointers, they are distinct and cannot always be used in place of each other.
Pointers and two dimensional Arrays: In a two dimensional array, we can access each element by using two subscripts, where first subscript represents the row number and second subscript represents the column number. The elements of 2-D array can be accessed with the help of pointer notation also.
A 2D array of pointers can be created following the way shown below. int *arr[5][5]; //creating a 2D integer pointer array of 5 rows and 5 columns. The element of the 2D array is been initialized by assigning the address of some other element.
The problem is that the compiler doesn't know the dimensions of your matrix.
When you have: double tab[m][n]
you can access the element tab[row][col]
as *(tab + (row * n) + col)
In your case you only have double *tab;
that can be considered as the pointer to the element tab[0][0]
with no information on the matrix dimensions and the compiler can't compute the right address.
You could compute the address yourself (for example using a macro) but would lose the nice tab[x][y]
syntax.
I`m surprised it compiles. You should have received at least a warning about implicitly casting a double to a pointer.
I'm very surprised it even compiles. Apparently c
is a double*
, so (&s->c)[m]
is the m'th double
. Now, double
doesn't have an operator[]
, so I don't see how the [n]
part in (&s->c)[m][n]
can be legal.
Presumably, you have declared c
differently. There are different solutions: a pointer to a pointer, an pointer to an array of doubles, an array of pointers to doubles, etcetera. All might work, if the allocations match the declaration. In your case, the allocation will not match the declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With