C – How to Dynamically Allocate a 2D Array in One Allocation

allocationc++mallocmultidimensional-array

Can you help me figure out how to allocate a 2D-array in one allocate call?

I tried to do:

int** arr = (int**)malloc(num * num * sizeof(int*));

But its doesn't work.

num is the rows and columns.

Best Answer

How can i to allocate dynamically array2D in 1 allocate C

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'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*));

Code can allocate memory for a 2D array and return a pointer to that memory. pointer to array 5 of array 6 of int

 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;

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;
Related Question