Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc a 2D array in C [duplicate]

Every time I allocate the memory for a 2D array first I create an array of int** and then with a for I allocate the memory for each element.

For example:

int ** arr = malloc(N*sizeof(int *));
for(i=0; i< N; i++) arr[i] = malloc(M*sizeof(int));

Wouldn't be possible allocate the memory like:

int ** arr = malloc(N*sizeof(int[M]));

or

int ** arr = malloc(sizeof(int[N][M]));

in order to avoid the for?

like image 259
ninazzo Avatar asked Apr 27 '16 13:04

ninazzo


1 Answers

You have a "pointer to pointer". That cannot represent a 2D array.

The correct declaration of a pointer to a 2D array is

// number of elements in one row
#define COLS 10

// number of rows
#define ROWS 20

int (*array)[COLS];   // mind the parenthesis!

That makes array a pointer to array of COLS ints. The type is `int (*)[COLS], btw. but you don't need the type, see below.

To allocate the array you should then use the standard allocation for a 1D array:

array = malloc(sizeof(*array) * ROWS);   // COLS is in the `sizeof`

array = malloc(sizeof(int[ROWS][COLS])); // explicit 2D array notation

Which variant to use is personal style. While the first contains no redundancy (consider you change the declaration of array to use INNER instead of COLS or the element-type to float). The second is more clear at a fist glance, but more prone to errors when modifying the declaration of array.

To free:

free(array);
like image 50
too honest for this site Avatar answered Oct 05 '22 18:10

too honest for this site