Intializing a 2D array in C++

Viewed 65

I am trying to initialize a 2d arary in the following code -

int main(void)
{
    int arr[][5] = {
        [0][1] : 1, [0][0] : 2, [0][2] : 3,
    };
    cout<<a[0][0]<<" "<<a[0][1]<<endl;

    return 0;
}

But the compiler gives me following error -

./2d-arr.cpp: In function ‘int main()’:
./2d-arr.cpp:7:4: error: expected identifier before numeric constant
   [0][1] : 1, [0][0] : 2, [0][2] : 3,
    ^
./2d-arr.cpp: In lambda function:
./2d-arr.cpp:7:6: error: expected ‘{’ before ‘[’ token
   [0][1] : 1, [0][0] : 2, [0][2] : 3,
      ^
./2d-arr.cpp: In function ‘int main()’:
./2d-arr.cpp:7:6: error: no match for ‘operator[]’ (operand types are ‘main()::<lambda()>’ and ‘int’)
./2d-arr.cpp:7:10: error: expected ‘}’ before ‘:’ token
   [0][1] : 1, [0][0] : 2, [0][2] : 3,
          ^
./2d-arr.cpp: At global scope:
./2d-arr.cpp:9:2: error: ‘cout’ does not name a type
  cout<<a[0][0]<<" "<<a[0][1]<<endl;
  ^~~~
./2d-arr.cpp:11:2: error: expected unqualified-id before ‘return’
  return 0;
  ^~~~~~
./2d-arr.cpp:12:1: error: expected declaration before ‘}’ token
 }
 ^

Whereas, if I replace ':' with '=' and compile it with gcc, it runs fine. My understanding so
far after googling the error message is that we can't initialize an array the same way we do in C.
Is there anything that can be done to the code above to make it working for C++ ?

1 Answers

I found the following code snapshot from here
which states that the above initialization is invalid for C++.

struct A { int x, y; };
struct B { struct A a; };
struct A a = {.y = 1, .x = 2}; // valid C, invalid C++ (out of order)
**int arr[3] = {[1] = 5};        // valid C, invalid C++ (array)**
struct B b = {.a.x = 0};       // valid C, invalid C++ (nested)
struct A a = {.x = 1, 2};      // valid C, invalid C++ (mixed)

Its not possible do designated initializing using [] in C++ as it is in C.

Related