Question

I will have multiple 2d int arrays..

int[5][5] A;
int[5][5] B;
int[5][5] C;

but how many I need is dependent on a parameter decided on runtime. How would I create a dynamic amount of 2D arrays and manage them?

Was it helpful?

Solution

In C you may use Variable Length Arrays (VLA). So you can declare one three dimensional array the left dimension of which will specify the number of two dimensional arrays.

For example

#include <stdlib.h>

int main( int argc, char * argv[] )
{
   // some check that the command line parameter was specified
   int a[atoi( argv[1] )][5][5];
}

OTHER TIPS

You can use:

int* myArr = malloc(x_dim*y_dim*sizeof(int)); // malloc guarantees contiguous memory allocation
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top