Home > Software engineering >  Foreach loop with multidimensional arrays in c
Foreach loop with multidimensional arrays in c

Time:12-17

I am getting an error while compiling the following cpp code:

int x[][2]{{1, 2}, {3, 4}};

for (int e[2] : x) {
    std::cout << e[0] << ' ' << e[1] << '\n';
}

This gives the following error:

error: array must be initialized with a brace-enclosed initializer

I did replaced int e[2] with auto e and that worked but I want to work with the actual type.

Is there any workaround?

CodePudding user response:

the correct fixed-size declaration is

for (int(&e)[2] : x) {}

or you can use auto& to deduce it

for (auto& e : x) {} // same as above

note: auto doesn't deduce the same type

for (auto e : x) {} // e is int*

CodePudding user response:

interpret the inner array as a pointer:

#include <iostream>
   
int main() {
    int x[][2]{{1, 2}, {3, 4}};

    for (int* e : x) {
        std::cout << e[0] << ' ' << e[1] << '\n';
    }
}
  • Related