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
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 elementtab[row][col]as*(tab + (row * n) + col)In your case you only have
double *tab;that can be considered as the pointer to the elementtab[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.