0

I have learned how to print out each element in a two-dimensional array

int arr[3][3] = {....};
for ( auto &row : arr){
     for ( auto col : row)
        cout<<col<<endl;
}

I understand that the &row in the outer for loop has to be a reference. Otherwise, row will become a pointer pointing to array arr's first element which is an array of 3 ints.

Based on this, I thought the following code could work but it didn't

for( auto row : arr ){
    for ( auto col:*row)
         cout<<col<<endl;
}

It gives me the error about the inner for loop

no callable 'begin' function found for type 'int'

Did I miss something here?

3
  • row is an array of 3 ints, which can be iterated. *row is an int, you can't loop through an integer.
    – tnt
    Mar 9, 2019 at 14:04
  • 1
    @tntxtnt row is a pointer, not an array (in the code that gives the error).
    – interjay
    Mar 9, 2019 at 14:11
  • Ah I didn't see row is not a reference in the second example.
    – tnt
    Mar 9, 2019 at 14:29

1 Answer 1

2

Each element of arr has type int[3].

When row is a reference, it gets type int (&) [3], which can be iterated over. But when it isn't a reference, the int[3] array decays to a pointer to its first element, so row has type int*, which can't be used in a range-for loop.

Your code is attempting to iterate over *row, which has type int, leading to the error.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.