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.

3
  • 2
    What's the C2059 error? Sure, I could google it, but should I google or answer your question? Commented Feb 9, 2011 at 15:51
  • 1
    Can you add the declaration of Variable ? Commented Feb 9, 2011 at 15:53
  • 1
    and also the declaration of row, please Commented Feb 9, 2011 at 15:54

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
    }
};

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.