在C中创建Mallocate数组函数

Jac*_*ber 2 c malloc segmentation-fault multidimensional-array

我有一个项目,我在C中创建几个动态的二维整数数组.

我试图通过创建mallocateArray函数来减少冗余代码.没有这个功能我可以让它工作.

问题是指针可能是一个麻烦,并且由于某种原因,当我尝试使用此方法时,我只是遇到了一个seg错误:

继承人我得到了什么:

     void mallocateArray(int ***array, int *row, int *col){
     //allocate storage for the array of ints:
         *array = (int**)malloc(*row * sizeof(int *));
         int i;
         for (i = 0; i < *row; i++){
            *array[i] = (int*)malloc(*col * sizeof(int));
         }
     }
Run Code Online (Sandbox Code Playgroud)

这是我的数组定义方式:

     int **matrix1,
     int row = 2
     int col = 3

     mallocateArray(&matrix1, &row, &col);
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到一个段错误.所以目前我只是不使用该方法并处理冗余.我试过搞乱指针,解除引用等等,但我似乎无法弄明白.

我希望你们能帮助我.

下面是我的main方法中的代码示例:

      result = (int**)malloc(row1 * sizeof(int *));
int i;
for (i = 0; i < row1; i++){
    result[i] = (int*)malloc(col2 * sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)

Car*_*rum 6

你很亲密 只是遗漏了一些括号.这一行:

*array[i] = (int*)malloc(*col * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

应该:

(*array)[i] = malloc(*col * sizeof(int));
Run Code Online (Sandbox Code Playgroud)

注意那些操作顺序!我也拿走了你不必要的演员.

如果你只是通过rowcol价值,你的功能将不那么复杂.例:

void mallocateArray(int ***array, int row, int col)
{
    *array = malloc(row * sizeof(int *));
    for (int i = 0; i < row; i++){
       (*array)[i] = malloc(col * sizeof(int));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果他返回一个`int**'而不是接受一个`int***`,那么他的函数将会变得更简单. (2认同)