对二维阵列使用malloc时出现分段错误
我使用对二维阵列使用malloc时出现分段错误,c,C,我使用malloc创建了一个二维数组。当我使用printf在for循环中打印数组元素时,一切正常。但是当我想在main中使用printf时,这是一个分段错误:11。 你能告诉我下面的代码有什么问题吗 #include <stdlib.h> #include <stdio.h> void initCache(int **cache, int s, int E){ int i, j; /* allocate memory to cache */ cache = (int *
malloc
创建了一个二维数组。当我使用printf
在for循环中打印数组元素时,一切正常。但是当我想在main中使用printf
时,这是一个分段错误:11。
你能告诉我下面的代码有什么问题吗
#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
}
#包括
#包括
void initCache(int**cache,int s,int E){
int i,j;
/*为缓存分配内存*/
cache=(int**)malloc(s*sizeof(int*);//集
对于(i=0;iprintf(“%d\n”,c[1][1]);//由于缓存是二维数组,它是int**
。要在函数中设置它,请传递int***
,而不是int**
。否则,在initCache
中对cache
所做的更改对main()
中c
的值没有影响
您更改了一个局部变量,这不会影响main中的局部变量c
如果要在函数中分配,为什么要传递变量?从函数中返回它
int **c = initCache(2, 2);
您可以使用返回
,或者按照其他人的建议使用***
。我将在这里介绍返回
方法
initCache
正在创建和初始化一个合适的数组,但它不会返回该数组。cache
是一个指向数据的局部变量。有两种方法可以使调用函数使用此信息。要么return
它,要么传入一个int***
并使用它记录指针值
我建议:
int** initCache(int **cache, int s, int E){
....
return cache;
}
main()
{
int **c;
c = initCache (2, 2);
printf("%d\n", c[1][1]); <<<<<<<<<< here
}
如果malloc失败,这将结束程序,并告诉您哪一行失败了。有些人(包括我!)会稍微不赞成这样使用assert
。但我们都同意这比不进行任何错误检查要好
您可能需要#包括
,以使此项工作正常。您更改了局部变量。
int **c = initCache(2, 2);
int** initCache(int **cache, int s, int E){
....
return cache;
}
main()
{
int **c;
c = initCache (2, 2);
printf("%d\n", c[1][1]); <<<<<<<<<< here
}
cache = (int **)malloc(s * sizeof(int *));
assert(cache);