C语言中二维数组的分配

3

我希望你能帮我翻译一下关于IT技术的内容。以下是需要翻译的内容:

我正在尝试分配一个二维维数组的文件描述符... 所以我需要像这样的东西     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个回答

3

首先,您需要传递指向myPipes的指针:

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

那么就很简单了:
*myPipes = malloc(sizeof(int) * rows * cols);

当然,你需要使用以下方式调用它:
int **somePipes;
allocateMemory(rows, cols, &somePipes);

2
简短回答:将最内层的malloc改为calloc。
长答案由C语言常见问题解答提供:http://c-faq.com/~scs/cclass/int/sx9b.html 你需要理解的是,C语言实际上没有一种分配真正多维数组的方法。相反,你只有一个指向指针数组的指针。将你的数据结构视为这样处理,就会没问题了。

链接已经失效,很遗憾。 - jupp0r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接