1

We usually initialize a 2D array like this:

int a[2][3] = {{2,3,4},{5,6,7}};

I need to initialize the 2D array like this:

int a[2][3];
a[0] = {2,3,4};
a[1] = {5,6,7};

i.e. I want initialize it array by array. Why does this method fail? What should I do? Or can I define a as array of array?

3
  • 5
    C++ does not have a syntax for array assignment. If you cannot do the first method you will have to write code to iteratively assign the 2d values. Commented May 12, 2015 at 3:05
  • I don't suppose std::array<std::array<int,3>,2> is an allowable alternative ? Commented May 12, 2015 at 3:11
  • initialization can be only done while declaration, else iterate Commented May 12, 2015 at 3:24

1 Answer 1

2

The idea of an array is to keep all the data in memory contiguous, this would not be achieved with the approach you are using, I would recommend using a C style memory management with RAW memory for a low level fast, thigh and possibly dangerous solution, or change to a different data container like the vector (or others) where you can add elements similar to what you want and the memory will still be contagious like the simple array. Although depending on the size of your problem it might be an overkill to use a vector.

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

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.