Search code examples
carrayspointersmemory-managementallocation

Allocate 2D Array in C (not array of pointers) in Heap


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.


Solution

  • 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.