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.

Leave a Comment