我使用malloc
创建了一个2-D数组。当我使用printf
在for循环中打印数组元素时,一切都很好。但是当我想在主要使用printf
时,这些是Segmentation fault: 11.
使用malloc作为二维数组时出现分段错误
请问您可以告诉我以下代码的问题是什么?
#include <stdlib.h>
#include <stdio.h>
void initCache(int **cache, int s, int E){
int i, j;
/* allocate memory to cache */
cache = (int **)malloc(s * sizeof(int *)); //set
for (i = 0; i < s; i++){
cache[i] = (int *)malloc(E * sizeof(int)); //int
for(j = 0; j < E; j++){
cache[i][j] = i + j;
printf("%d\n", cache[i][j]);
}
}
}
main()
{
int **c;
initCache (c, 2, 2);
printf("%d\n", c[1][1]); // <<<<<<<<<< here
}
你改变了局部变量。 –