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.
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
Let us start with what is a 2D array:
Example of a 2D array or "array 3 of array 4 of int"
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.
Code can allocate memory for a 2D array and return a pointer to that memory. pointer to array 5 of array 6 of int
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