Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heap allocate a 2D array (not array of pointers)

I am writing C code and I would like to heap allocate 512*256 bytes. For my own convenience I would like to be able to access the elements with the syntax array[a][b]; no arithmetic to find the right index.

Every tutorial I see online tells me to create an array of pointers that point to arrays of the rows I want in my array. This means that each subarray needs to be malloc'd and free'd individually. I am interested in a solution that only requires one call to malloc and one call to free.(Thus all elements are contiguous) I think this is possible because I will not be constructing a jagged array.

I would appreciate if anyone could share the syntax for declaring such an array.

like image 617
Paul Avatar asked Sep 05 '25 03:09

Paul


2 Answers

Well, if you want to allocate array of type, you assign it into a pointer of that type.

Since 2D arrays are arrays of arrays (in your case, an array of 512 arrays of 256 chars), you should assign it into a pointer to array of 256 chars:

char (*arr)[256]=malloc(512*256);
//Now, you can, for example:
arr[500][200]=75;

(The parentheses around *arr are to make it a pointer to array, and not an array of pointers)

like image 108
asaelr Avatar answered Sep 07 '25 22:09

asaelr


This is easy assuming you don't need compatibility with the ancient C89 standard (among current C compilers, only MSVC and a few embedded-target compilers are that backwards). Here's how you do it:

int (*array)[cols] = malloc(rows * sizeof *array);

Then array[a][b] is valid for any a in [0,rows) and b in [0,cols).

In the language of the C standard, array has variably-modified type. If you want to pass the pointer to other functions, you'll need to repeat this type in the function argument list and make sure that at least the number of columns is passed to the function (since it's needed as part of the variably-modified type).

Edit: I missed the fact that OP only cares about a fixed size, 512x256. In that case, C89 will suffice, and all you need is:

int (*array)[256] = malloc(512 * sizeof *array);

The exact same type can be used in function argument lists if you need to pass the pointer around between functions (and also as a function return type, but for this use you might want to typedef it... :-)

like image 41
R.. GitHub STOP HELPING ICE Avatar answered Sep 07 '25 22:09

R.. GitHub STOP HELPING ICE