2013-10-06 104 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>才能完成此項工作。