Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocate contiguous memory for a "rectangular 2d array", without using VLAs

This is one of those questions where there are so many answers, and yet none do the specific thing.

I tried to look at all of these posts — 1 2 3 4 5 6 7 8 9 — and every time the solution would be either using VLAs, using normal arrays with fixed dimensions, or using pointer to pointer.

What I want is to allocate:

  • dynamically (using a variable set at runtime)
  • rectangular ("2d array") (I don't need a jagged one. And I guess it would be impossible to do it anyway.)
  • contiguous memory (in #8 and some other posts, people say that pointer to pointer is bad because of heap stuff and fragmentation)
  • no VLAs (I heard they are the devil and to always avoid them and not to talk to people who suggest using them in any scenario).

So please, if there is a post I skipped, or didn't read thoroughly enough, that fulfils these requirements, point me to it.
Otherwise, I would ask of you to educate me about this and tell me if this is possible, and if so, how to do it.

like image 588
iloveclang Avatar asked Oct 12 '25 11:10

iloveclang


1 Answers

You can dynamically allocate a contiguous 2D array as

int (*arr)[cols] = malloc( rows * sizeof (int [cols]) );

and then access elements as arr[i][j].

If your compiler doesn’t support VLAs, then cols will have to be a constant expression.

like image 157
John Bode Avatar answered Oct 15 '25 04:10

John Bode