DEV Community

Paul J. Lucas
Paul J. Lucas

Posted on

Dynamically Allocating 2D Arrays Efficiently (and Correctly!) in C 2.0

#c

Introduction

In my article Dynamically Allocating 2D Arrays Efficiently (and Correctly!) in C, I showed how to do exactly that by allocating a buffer then using pointers within it to point to the start of rows later in the same buffer.

It was recently pointed out to me by a reader that there’s a much simpler way to do it.

The Simpler Way

If you want to allocate an m × n 2D matrix, you can much more simply do:

int (*const a)[m] = malloc( m * n * sizeof(int) );
a[i][j] = 42;  // works
free( a );
Enter fullscreen mode Exit fullscreen mode

where a is a constant pointer to an array of m integers. Although it’s using variable length array (VLA) syntax, it’s not allocating a VLA on the stack since malloc is being used. Yet the compiler is still generating VLA-like code in order to calculate the offset of the ith row at runtime, that is multiplying m × sizeof(int) — a variable, not a constant integer expression.

The only caveat is that gcc with the -Wvla warning enabled complains that a VLA is being used. I mean, it is sort-of, but not the allocate-on-the-stack part which is the dangerous part. The above code is safe in that it can’t overflow the stack.

Note that if you want to allocate a triangular matrix, then you’ll still need to use the method I described in my previous article.

Conclusion

It just goes to show that even after as long as I’ve been doing C, there’s still something to learn about it.

Top comments (0)