Thursday, April 12, 2012

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 on call to malloc and 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.





No comments:

Post a Comment