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.

madu
  • 5,232
  • 14
  • 56
  • 96
  • What is the relevance of the 2D? – juanchopanza Mar 19 '18 at 06:50
  • @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. – madu Mar 19 '18 at 07:15
  • 1
    @madu It's no duplicate, because the other answer is in C and the solution from C doesn't work for C++. – ArchLinuxTux Mar 19 '18 at 14:41
  • 1
    If someone needs to do this in C, [here is how](https://stackoverflow.com/questions/8886375/possible-to-initialize-an-array-after-the-declaration-in-c) with this one: `char (*daytab)[3] = (char [][3]){{1, 31, 4}, {2, 31, 4}};` for multidimensional arrays. – ArchLinuxTux Mar 21 '18 at 07:36

2 Answers2

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).

dontpanic
  • 341
  • 2
  • 8
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;
Beyondo
  • 2,952
  • 1
  • 17
  • 42
  • Thank you. This is not quiet possible because arr is actually a [10][11] array. – madu Mar 19 '18 at 07:00
  • 2
    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. – Beyondo Mar 19 '18 at 07:06