A different way to malloc a 2D array?

So shouldn't the following be the correct way to dynamically allocate a 2d array?

It should, since this approach is the equivalent of declaring a "statically-allocated" array of multiple dimensions.

The reason for this is that this way, you get a contiguous block of memory, which is convenient (you couldn't use memset() on a pointer-to-pointer, right?), and you still can have the compiler do the pointer arithmetic and array subscripting calculation for you (that's convenient too).

By the way, if you need a dynamically-sized array of which the scope is only within one function, i. e. you don't need to return it, consider using a VLA (variable-length array) with automatic storage duration instead.


Your 2D array isn't fully dynamic since one of its dimensions is fixed to two elements. (In your particular example, you could use a variable-length array, but in general you might want to be able to return your allocated array from a function.)

If you want something that syntactically acts like a 2D M×N array, is allocated completely dynamically, and uses contiguous memory, you can allocate a block of memory of M * N elements and then allocate an array of M pointers, where each element points to a "row' of the M * N block.

Q6.16 from the comp.lang.c FAQ has a good diagram and a more detailed explanation of this.

(Okay, it's not completely contiguous since the array of pointers and the block of items are separate. You could allocate both of them together, although that's trickier since it'd require some extra work to guarantee proper alignment.)