0

I am having trouble initializing a 2D int array. The structure of my program is:

int arr[2][2];
if(val==1)
 arr = {{1,1}, {2,2}};
else if (val==2)
 arr = {{3,3}, {4,4}};
...
...

int x = arr[1][1];
...

I am getting an error "Expression must be a modifiable lvalue"

Thanks.

5
  • What is the relevance of the 2D? Commented Mar 19, 2018 at 6:50
  • 1
    @ArchLinuxTux do you believe the accepted answer here is a duplicate of the answer of your question? I fail to see how they are duplicates. The accepted answer of using array<> is the right way to go about this and it was not part that answer. Commented Mar 19, 2018 at 7:15
  • 1
    @madu It's no duplicate, because the other answer is in C and the solution from C doesn't work for C++. Commented Mar 19, 2018 at 14:41
  • 1
    If someone needs to do this in C, here is how with this one: char (*daytab)[3] = (char [][3]){{1, 31, 4}, {2, 31, 4}}; for multidimensional arrays. Commented Mar 21, 2018 at 7:36
  • @madu (I am grown-up ArchLinuxTux) i just sometimes click the duplicate question button and then stackoverflow auto-generates these comments... Commented Dec 31, 2024 at 14:27

2 Answers 2

7

In your code, arr = {{1,1}, {2,2}}; is not initialization. If you insist on the native array, I'm afraid you have to manually set each element.

However you can switch to use std::array, which gives what you want:

array<array<int, 2>, 2> arr;
if (val == 1)
    arr = { { { 1,1 }, { 2,2 } } };
else if (val == 2)
    arr = { { { 3,3 }, { 4,4 } } };

int x = arr[1][1];

Note the extra braces (see here).

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

1 Comment

with c++14 extra-braces are not needed anymore.
3

Initializing

int arr[2][2] = {{3,3}, {4,4}};

modifying

arr[0][0] = 3;
arr[0][1] = 3;
arr[1][0] = 4;
arr[1][1] = 4;

2 Comments

Thank you. This is not quiet possible because arr is actually a [10][11] array.
this is the way for int types, you're still able to loop and make things easier, or since you mentioned C++, things are more comfortable with its provided libraries.

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.