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:
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.
You don't need a special function. Just do it like this
double (*A)[n][m] = malloc(sizeof *A);
As of C99, here n
and m
can be any positive integer expressions you want.
Such a thing is a pointer to a VLA, variable length array.