2010-04-06 82 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);