Multi-demential array in class

Hey everybody, im trying to initialize a multi-demential array in a class constructor - How would i be able to do that ?

I tried doing this but it didnt work
1
2
3
4
5
6
7
class Foo {
public:
   Foo(int i_Tiles[40][30]): Tiles(i_Tiles) {}

private:
    int Tiles[40][30];
};

Im getting the error

array initializer must be an initializer list
Last edited on
You can't assign arrays like that. What you're doing is equivalent to
1
2
int i_Tiles[40][30];
int Tiles[40][30] = i_Tiles;

Which is invalid for arrays. You can loop through each element of the array if you want to initialize it, or you can use pointers instead.
Last edited on
Can you demonstrate how to use pointers to initialize it?
I'm not sure if there's a way to do it without using dynamic memory (i.e. the new keyword). But using dynamic memory it would look something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Foo {
public:
  Foo(int **i_Tiles): Tiles(i_Tiles) {}

private:
  int **Tiles;
};

int main() {
  int **i_Tiles;
  i_Tiles = new int*[40];
  for (int i = 0; i < 40; i++) {
      i_Tiles[i] = new int[30];
  }
  Foo foo(i_Tiles);
}


Alternatively, if you use vectors, you should be able to pass those to the constructor. Then you wouldn't need to worry about dynamic memory.
Last edited on
Is there anyway i would be able to use stack allocated memory then just pass a pointer to the class then use it to copy each item?
closed account (o1vk4iN6)
Just use a for loop ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

class Food
{
public:
     static const int TILES_ROWS = 30;
     static const int TILES_COLUMNS = 40;
     static const int TILES_NUM = TILES_ROWS * TILES_COLUMNS;
     
     Food( int tiles[ TILES_ROWS ][ TILES_COLUMNS ] )
     {
          int* p = reinterpret_cast< int* >( this->tiles );
          int* ip = reinterpret_cast< int* >( tiles );

          for(int i = 0; i < TILES_NUM; ++i)
               p[ i ] = ip[ i ];
     }

private:
     int tiles[ TILES_ROWS ][ TILES_COLUMNS ];

};



I need them to be the same memory, like when i change a value in the passed in array it will also change the value in the tiles in the array
closed account (o1vk4iN6)
Why have a reference at all ? Just store the array in the class and overload the operator[] so you can access and modify it like an array.
Never mind, i fixed it by allocating it on the heap then just passed in the pointer as Gulshan suggested, but thank you both.
closed account (o1vk4iN6)
You don't need to allocate an array to be able ot make 2D that is only if you don't know the dimension at compile time. How to allocate and store the pointer for a 2D array.

int (* tiles)[30] = new int[40][30];

I hope you are freeing the memory properly btw.

I still think it would be better for the class to handle the allocation on it's own, it doesn't make sense and can cause error like if you free the array before the class is destructed.
Topic archived. No new replies allowed.