So, shouldn't there be a proper way to dynamically allocate a 2d array?
It should , because this approach is the equivalent of declaring an array of “statically assigned” multiple dimensions.
The reason for this is that in this way you get a continuous block of memory that is convenient (you cannot use memset() to pointer to a pointer, right?), And you can still have the compiler do the calculation of the pointer arithmetic and the calculation of the array substring for you (this is also convenient).
By the way, if you need an array with dynamic size, the scope of which is only within the same function, then i. e. you do not need to return it, consider using a VLA (variable length array) with automatic storage duration.
user529758
source share