Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对二维阵列使用malloc时出现分段错误_C - Fatal编程技术网

对二维阵列使用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);