Multidimensional array & pointer in range for loops
not working:
// range for
for (int (*row)[4] : ia) {
for (int col : *row)
cout << col << " ";
cout << endl;
}
// error: cannot convert 'int*' to 'int (*)[4]' in initialization.
working:
// range for
for (int (&row)[4] : ia) {
for (int col : row)
cout << col << " ";
cout << endl;
}
yet, i thought either code is similar, either i confused about how pointer works / how range for iteration works. either way, the first code produce type error which should not be there if the second code is working. :/
Vastor
Junior Poster in Training
84 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
There is a nice and short explanation about the difference in between derefence and reference operators here:
http://www.cplusplus.com/doc/tutorial/pointers/
These two operators can be tricky sometimes. I know it from my own experience. ;)
CGSMCMLXXV
Junior Poster in Training
54 posts since Jan 2013
Reputation Points: 5
Solved Threads: 7
Skill Endorsements: 0
I'm sure I'm doing it right.
Source: C++ primer 5th edi.
Note
The parentheses in this declaration are essential:
Click here to view code image
int ip[4]; // array of pointers to int
int (ip)[4]; // pointer to an array of four ints
and as we know pointer hold the address, so *row should work to obtain the object but not in the code snippet because of "type clash".
that's why I'm actually wonder how range for iteration works, maybe that's the cause.
i even try some random method but it seems I'm out of luck, anyone can clarify why this happen?
Vastor
Junior Poster in Training
84 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
either way, the first code produce type error which should not be there if the second code is working. :/
Each element of a two-dimensional array is a one-dimensional array.
Not a pointer to a one-dimensional array.
int a[20] ;
for( int& i : a ) i = 0 ; // fine; the type of element of 'a' is 'int'
for( int* pi : a ) *pi = 0 ; // *** error ***
// the type of element of 'a' is not 'pointer to int'
Likewise,
int b[10][4] ;
// fine; the type of element of 'b' is 'int[4]', 'array of 4 integers'
for( int (&row)[4] : b ) for( int& i : row ) i = 0 ;
// the type of element of 'b' is not 'int(*)[4]', 'pointer to array of 4 integers'
for( int (*ptr_row)[4] : b ) for( int& i : *ptr_row ) i = 0 ; // *** error ***
vijayan121
Posting Virtuoso
1,740 posts since Dec 2006
Reputation Points: 1,236
Solved Threads: 320
Skill Endorsements: 11