Hello C++ coders ,
First of all, I am sorry for the poor subject for this post. I do not what this actually should be called. I have a piece of a syntax that I really could not understand.
int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
int(&row)[4] = ia[1];
If someone can be so kind and explain what this code does, I would appreciate that.
#include<iostream>
int main(){
int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
for ( auto r : ia ) {
for ( int c=0; c<4; ++c ) {
std::cout << " " << r[c];
}
// for ( auto e : r ) { // ERROR, the r is not an array
// std::cout << " " << e;
// }
std::cout << '\n';
}
std::cout << '\n';
int (&row)[4] = ia[1];
for ( int c=0; c<4; ++c ) {
std::cout << " " << row[c];
}
std::cout << "\n\n";
for ( auto e : row ) { // OK, the row is an array
std::cout << " " << e;
}
std::cout << "\n\n";
row[2] = 42; // modifies ia
for ( auto r : ia ) {
for ( int c=0; c<4; ++c ) {
std::cout << " " << r[c];
}
std::cout << '\n';
}
return 0;
}
The 'row' object looks like an array with known size. It is actually a reference to array; not a copy.
Usually (e.g. as function argument) array is decayed to a pointer, which does not know the size of array.
There is also an array pointer:
1 2 3 4 5 6 7 8
int ia[3][4] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
int (*foo)[4] = ia;
for ( int r=0; r<3; ++r ) {
for ( auto e : foo[r] ) {
std::cout << " " << e;
}
std::cout << '\n';
}
In the pointer 'foo' a size (4) is retained, but it affects pointer math.
When we write auto bar = foo + 1;, the '+1' is actually +1*(4*sizeof(int)) bytes.