2013-10-06 79 views
-1

我使用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 

} 
+4

你改变了局部变量。 –

回答

3

你改变了一个局部变量,不会在主要作用的局部变量c

如果你想在函数中分配,为什么要传递一个变量?从功能中返回。

int **c = initCache(2, 2); 
4

由于您的缓存是二维数组,因此它是int**。要在函数中设置它,请通过int***,而不是int**。否则,对initCache内部产生的cache的更改对c的值从main()没有影响。

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]); 
     } 
    } 
} 

现在你可以这样调用:

initCache (&c, 2, 2); 
1

你可以使用一个return,要不然***由他人建议。我将在这里描述return方法。

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将返回NULL。此外,您可能会意外地注意到负数的内存(如果s为负数)。所以我会这样做:

cache = (int **)malloc(s * sizeof(int *)); 
assert(cache); 

这将结束程序,如果malloc失败,并告诉你什么行失败。有些人(包括我!)会稍微反对使用assert。但是我们都会同意它比没有任何错误检查更好!

您可能需要#include <assert.h>才能完成此项工作。