I have a simple question, but the answer seems to be very difficult to find:
How do I create a true 2D array in C (not C++), dynamically sized (size not known at compile time), not an array of pointers, on the heap, so that I can put that allocation into a separate function and return the allocated array, without receiving any warnings from gcc -Wall
?
I've found numerous other questions here on SO and in other forums, but the answers all had some flaw:
- I saw many answers, which showed how to initialize an array of pointers, which according to some comments can lead to memory fragmentation and needs a loop to be freed when not used anymore.
- I don't want to only have a predefined size of the array, but want to use it in some loops, creating arrays of many sizes.
- I don't want the values in the array to be predefined either, they're calculated while the program is running.
- I read about the layout in the memory, which can be different when using some methods of creating the array, while one can still use the array like this:
a[y][x]
. I want my array to have the memory layout of a true 2D array as well.
What is the right way to achieve allocation of such a true 2D array?
EDIT#1: The return type of the allocation method can be a pointer to the allocated array.
&array[x][y]
is. (To compute the addressarray + x
,sizeof(array[0])
must be known). – molbdnilo