0

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Jordan H
  • 181
  • 1
  • 2
  • 11

2 Answers2

2

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];
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So essentially a[0][5][5] and a[1][5][5]are A[5][5] and B[5][5] ? – Jordan H Mar 30 '14 at 00:33
  • Fantastic, I appreciate it. Is this a common way of handling this in C? – Jordan H Mar 30 '14 at 00:34
  • @Jordan H I do not know whether it is a common way or not. The idea came to me just now. Your compiler must support C99. – Vlad from Moscow Mar 30 '14 at 00:36
  • 1
    @JordanH: not knowing how many arrays you'll need until runtime is a fairly unusual requirement; Vlad's suggestion is about as good as you'll get. The alternative is using dynamic memory allocation with `malloc()` et al; that too gets hairy (and as long as the total size of the arrays is small enough to fit on your stack), VLAs are notationally very convenient. – Jonathan Leffler Mar 30 '14 at 00:45
  • You should check if the command-line parameter was specified; otherwise, the program will give a segmentation fault. – S.S. Anne Aug 18 '19 at 15:56
-1

You can use:

int* myArr = malloc(x_dim*y_dim*sizeof(int)); // malloc guarantees contiguous memory allocation
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
deeiip
  • 3,319
  • 2
  • 22
  • 33