Dynamic stride in a matrix (1d mimics 2d)

Hey, so this is one of those posts I’m creating so I can link it to beginners when they ask about 2D arrays and creating arrays in C++ with a user defined size at runtime. C++, being a child of C, is very picky about how and when you ask for memory to use for storage. This int arr[10] creates a “c-style” static array on the stack. The size must be known at compile time and it can not be changed at runtime. If you try to do
std::cin >> size;
int arr[size];
you should get an error. Unfortunately GCC and CLang both ship with VLA (variable length arrays) turned on by default so unless you add a specific compiler flag the above code will compile. But, to the topic at hand. If you want to create an array using size determined at runtime you have to either use an stl container like std::vector (which is the smart thing to do 99% of the time) or you have to use new and delete to ask for some memory on the heap for your array and then to free that allocation when you’re done with it. Which is pretty straight forward:

int size = 0;
std::cin >> size;
int* arr = new int[size];
//... do stuff with arr
delete[] arr;

No big deal, but what if you want a matrix or some kind of 2D representation of data like
[0, 1, 2]
[3 ,4, 5]

[6, 7, 8]
again easy enough to create a static 2d array at compile time with
int arr[3][3];
and then fill it up but what if you need to find the sizes of your rows and columns at runtime? Welcome to the nightmare of allocating 2d dynamic arrays

int rows = 0, cols = 0;
std::cin >> rows >> cols;
int** my2Darr = new int*[rows];
for(int i = 0; i < cols; i++)
   my2Darr[i] = new int[cols];

and that’s just to get your array allocated, when you’re done with it you have to write a bunch of cleanup code like:

for(int i = 0; i < cols; i++)
    delete[] my2Darr[i];
delete[] my2Darr;

That’s no fun. It’s much easier to use a 1D array to emulate a 2D array and then use a stride(or offset) to navigate the structure. Basically you lay the 2 dimensions out in a line and the stride is the offset. If you use a nested loop the stride formula is i * cols + j or row * columns + column
So if we want a 5 * 5 array that hold the numbers 1 -25 in rows of 5 we can use this code

int rows = 5, cols = 5, count = 1;
int* matrix = new int[rows * cols];
for(int row = 0; row < rows; row++)
    for(int col = 0; col < cols; col++)
        matrix[row * cols + col] = count++;
// when we're done we clean up with a simple
delete[] matrix;

Again it’s generally best to use stl containers or a matrix library like glm but this often comes up when folks are learning the basic of C++ so I thought it good to write a post exploring dynamic 2D(and 1D) arrays.

Stride is a popular tool to navigate buffers in libraries like OpenGL
And here is a link to Compiler Explorer with the complete code: