我使用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
}
你改變了局部變量。 –