我在我的main()
块中声明了一个 2D 锯齿状数组。这将被传递给函数以分配内存。以下是最精简的情况,它编译但在运行时崩溃。我哪里错了?
#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");
}
这会读取值,但当我输入低数字(即“1 1”)时会崩溃,但当我输入高数字(即“10 10”)时会崩溃。