在函数内动态分配2D数组(使用指针返回已分配对象的地址)

我想知道如何使用函数参数将指针传递给动态分配的数组。 该函数应该分配数组10×10(为简单起见,跳过检查)。 这可能吗? 我究竟做错了什么? 提前致谢。

int array_allocate2DArray ( int **array, unsigned int size_x, unsigned int size_y) { array = malloc (size_x * sizeof(int *)); for (int i = 0; i < size_x; i++) array[i] = malloc(size_y * sizeof(int)); return 0; } int main() { int **array; array_allocate2DArray (*&array, 10, 10); } 

尝试这样的事情:

 int array_allocate2DArray (int ***p, unsigned int size_x, unsigned int size_y) { int **array = malloc (size_x * sizeof (int *)); for (int i = 0; i < size_x; i++) array[i] = malloc(size_y * sizeof(int)); *p = array; return 0; } int **array; array_allocate2DArray (&array, 10, 10); 

我使用临时p来避免混淆。

当我遇到类似的问题时,我遇到过这篇文章(我正在寻找一种在C中动态分配字符串数组的方法)。 我更喜欢从函数返回数组指针。 以下为我工作(我为你的整数数组调整了它)。 我随意为每个值设置99,所以我可以看到它们在main中打印出来。

 int **array_allocate2DArray(unsigned int size_x, unsigned int size_y) { int i; int **arr; arr = malloc(size_x*(sizeof(int*))); for (i=0 ; i