0

I have a 2D array which I declared part of the classes private members. When I call the constructor, I start assigning values to the 2D array. But every time I do so, I'm hit with an error C2059. To make sure nothing else was causing that error I commented out that line and the compiler finished putting together a binary file.

tried:
Variable[row] = { 0, 1, 2, 3};
Variable[row][] = { 0, 1, 2, 3};
Variable[row][4] = { 0, 1, 2, 3};

No luck, any clues. Thanks in advance.

Nocturnal
  • 683
  • 7
  • 25

3 Answers3

3

This syntax is only to be used for the creation of the object.

int array[4] = {1, 2, 3, 4};

Once the array is created, you have to use a loop to assign values to it.

Here's a short example :

class A
{
    int array[4];

    public:
    A()
    {
        // Here, array is already created
        // You can _assign_ values to it
    }
};

If you want to give it values when it's instantiated in the constructor, the only way is to use initialization lists. Unfortunatly, you can't do this with a static array.

See this this thread.

Community
  • 1
  • 1
fouronnes
  • 3,838
  • 23
  • 41
1

Unfortunately, we can't yet properly initialize arrays that are members of classes. I don't know exactly how yours is declared, but here's an example of what to do:

class X
{
    int Variable[3][4];

public:
    X()
    {
        const int temp[][4] = { { 1, 2, 3, 4}, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
        const int sz = sizeof(Variable)/sizeof(**Variable);
        std::copy(*temp, (*temp) + sz, *Variable);
    }
};
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
0

Since your question is not clear enough, all I can do is demonstrating a simple example.

2D array is initialized as,

//you may "optionally" provide the size of first dimension 
int arr[][4]  = {
          {1,2,3,4},
          {11,12,13,14},
          {21,22,23,24}
        };

And is acessed as,

for ( int i = 0 ; i < 3 ; ++i )
{
      for ( int j = 0 ; j < 4 ; ++j )
      {
          cout << arr[i][j] << endl;
      }
}

Online demonstration at ideone : http://www.ideone.com/KmwOg

Are you doing similarly?

Nawaz
  • 353,942
  • 115
  • 666
  • 851