I have a 2D jagged array declared in my main() block. This is to be passed to a function to have memory allocated to it. The following is the most reduced case which compiles but crashes when it runs. Where am I going wrong?
#include <stdio.h>
#include <stdlib.h>
void alloc2d(double ***p);
int main () {
double **data;
alloc2d(&data);
printf("Before assign to data\n");
data[0][0] = 0.1;
printf("After assign to data\n");
free(data);
}
void alloc2d(double ***p) {
int i, n, m;
// Get some dynamically assigned sizes
printf("Enter size: ");
scanf("%d %d", &n, &m);
// Now allocate
*p = malloc(n * sizeof(double*));
for (i = 0; i < n; i++) {
*p[i] = malloc(m * sizeof(double));
}
printf("End of alloc2d\n");
}
This reads the values but crashes when I enter low numbers (i.e. ‘1 1′) but crashes when I enter high numbers (i.e. ’10 10’).
You made a very simple syntax error
should really be
This is because in C, [] operator has higher precedence than *.
So when you type
*p[i],it is translated into
**(p + i).This means: you are asking the compiler to calculate the address by offsetting the address of p by
i * sizeof(double**), which is clearly not what you actually want.So, in order to force the compiler to dereference p first, simply surroud
*pwith brackets.