0

Possible Duplicate:
How do I use arrays in C++? (FAQ)
Using dynamic multi-dimensional arrays in c++

void fillTestCase (int * tC)
{
    ifstream infile;
    infile.open("input00.txt",ifstream::in);
    int * tempGrid;
    int i,j;
    infile >>i;
    infile >>j;
    tempGrid = new int[i][j];
}

gives me an error:

error C2540: non-constant expression as array bound
error C2440: '=' : cannot convert from 'int (*)[1]' to 'int *'

how can I make this two demensional array dynamic?

Community
  • 1
  • 1
moesef
  • 4,641
  • 16
  • 51
  • 68
  • 1
    First related question: http://stackoverflow.com/questions/1471721/using-dynamic-multi-dimensional-arrays-in-c?rq=1 – chris Jul 07 '12 at 20:08
  • 2
    Just throwing it out there, too: Use `std::vector` instead if you can. – chris Jul 07 '12 at 20:14
  • 1
    SO's C++ FAQ entry for arrays ___[How do I use arrays in C++?](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c)___ has a few paragraphs on multi-dimensional arrays. – sbi Jul 07 '12 at 20:18

2 Answers2

1

The easiest way is to make the array onedimensional, and calculate the indices yourself.

Pseudocode:

int MaxWidth;
int MaxHeight;
int* Array;

Array=new int[MaxWidth*MaxHeight];

int Column, Row;
...

Element=Array[Row*MaxWidth+Column];
Christian Stieber
  • 9,954
  • 24
  • 23
1

By far the nicest way would be to use the boost multidimensional array library.

Their example for a 3-d array:

int main ()
{
  // Create a 3D array
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;

  for ( int x = 3; x < 5; ++x )
  {
      int y = 4, z = 2;

      array_type A(boost::extents[x][y][z]);

      // Assign values to the elements
      int values = 0;
      for(index i = 0; i != x; ++i) 
        for(index j = 0; j != y; ++j)
          for(index k = 0; k != z; ++k)
            A[i][j][k] = values++;

      // Verify values
      int verify = 0;
      for(index i = 0; i != x; ++i) 
        for(index j = 0; j != y; ++j)
          for(index k = 0; k != z; ++k)
            assert(A[i][j][k] == verify++);
    }

  return 0;
}
Alex Wilson
  • 6,690
  • 27
  • 44