我如何在一个分配C中动态分配2D数组 [英] How can I dynamically allocate 2D-array in one allocate C
问题描述
您能帮我弄清楚如何在一个分配调用中分配2D数组吗?
Can you help me figure out how to allocate a 2D-array in one allocate call?
我试图做:
int ** arr =(int **)malloc(num * num * sizeof(int *));
int** arr = (int**)malloc(num * num * sizeof(int*));
但是它不起作用.
num
是行和列.
推荐答案
如何在1个分配C中动态分配array2D
How can i to allocate dynamically array2D in 1 allocate C
让我们从2D数组开始:
Let us start with what is a 2D array:
Example of a 2D array or "array 3 of array 4 of int"
int arr1[3][4];
arr1[0][0] = this;
OP的代码声明了指向int的指针,而不是2D数组或2D数组的指针.
顺便说一句,不需要强制转换.
OP's code declares a pointer to pointer to int, not a 2D array nor a pointer to a 2D array.
BTW, the cast in not needed.
int** arr = (int**)malloc(num * num * sizeof(int*));
代码可以为2D数组分配内存,并返回指向该内存的指针. 指向int数组6的数组5的指针
int (*arr2)[5][6] = malloc(sizeof *arr2);
if (arr2 == NULL) return EXIT_FAILURE;
(*arr2)[0][0] = this;
return EXIT_SUCCESS;
// or with Variable Length Arrays in C99 and optionally in C11
int (*arr3)[num][num] = malloc(sizeof *arr3);
(*arr3)[0][0] = that;
或者,代码可以为一维数组分配内存,并返回指向该内存的指针. 指向int数组8的指针.有时,这通常是人们想要的带有分配2D"数组的东西,实际上是指向1D数组的指针
Alternatively code can allocate memory for a 1D array and return a pointer to that memory. pointer to array 8 of int. Sometimes this is often what one wants with with an "allocate 2D" array, really a pointer to a 1D array
int (*arr4)[8] = malloc(sizeof *arr4 * 7);
arr4[0][0] = this;
// or
int (*arr5)[num] = malloc(sizeof *arr5 * num);
arr5[0][0] = that;
这篇关于我如何在一个分配C中动态分配2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!