2010-04-06 89 views
3

我試圖分配文件描述符2D維數組...所以我需要像這樣 FD [0] [0] FD [0] [1]Ç分配兩個多維數組

到目前爲止,我已經編碼:

void allocateMemory(int row, int col, int ***myPipes){ 
    int i = 0,i2 = 0; 
    myPipes = (int**)malloc(row * sizeof(int*)); 
    for(i = 0; i < row;i++){ 
     myPipes[i] = (int*)malloc(col * sizeof(int)); 
    } 
    } 

如何設置這一切太零,現在我不斷收到一個賽格故障時,我嘗試分配一個值...

感謝

回答

2

簡短回答:將您最內層的malloc更改爲calloc。由C常見問題提供

長回答: http://c-faq.com/~scs/cclass/int/sx9b.html

你需要了解什麼是,C並沒有真正有辦法來分配一個真正的多維數組。相反,你只需要一個指向數組指針的指針。對待你的數據結構,你會沒事的。

+0

完美謝謝! – Jacob 2010-04-07 00:10:26

+0

不幸的是,鏈接已經死亡。 – jupp0r 2013-08-22 10:29:35

3

因此,首先,你將有一個指針傳遞給myPipes

void allocateMemory(int rows, int cols, int ***myPipes) { ... } 

然後,它很簡單:

*myPipes = malloc(sizeof(int) * rows * cols); 

和當然,你會跟調用它:

int **somePipes; 
allocateMemory(rows, cols, &somePipes);