Re: pointer arithmetic and multi-dimensional arrays
Thanks a lot, for your answer, Alf! There are some things I still don't
understand, though (and yes, it's homework-related, but not my homework
but that of my students).
Alf P. Steinbach wrote:
#include<iostream>
int main()
{
int a[2][3] = { {0, 1, 2}, {3, 4, 5} };
int* first = a[0]; // pointer to a[0][0]
// loop 1
for (int* p = first; p < first+6; ++p)
std::cout << *p; // 012345
// loop 2
for (int* p = first; p < first+6; p+=2)
std::cout << *p; // 024
return 0;
}
You have no guarantee that a pointer to the first array element can be
treated as a pointer to the array. On a segmented architecture the
pointers might theoretically (although not in practice) be completely
different beast, and the two inner arrays might reside in different
segments, "you can't get there from here".
This seems to be in contradiction to [dcl.array] 1 where it is stated
that "An object of array type contains a contiguously allocated nonempty
subset of N subobjects of type T". And a twodimensional array is simply
an array where T is another array type.
In loop 2,
if p == first+2 (pointer to last element of a[0]), p+=2 points to
the second element of a[1], so p and p+=2 do not refer to the same
array. In this case, [expr.add] 5 stipulates undefined behavior.
The reasoning here seems to not be meaningful in any way, but the
conclusion is just about right.
The reasoning was based on the assumed fact that the two subarrays are
contiguoulsy allocated in memory.
On the suspicion that this is HOMEWORK, I'll leave it as an exercise to
figure out why the second loop has formally Undefined Behavior in
addition to the UB considerations that apply to the first loop.
I figured one thing out that also applies to loop 1 (stupid me): the
behavior of the operation "first+6" is already undefined since first and
the result first+6 definitely do not point to elements (or past the end)
of the same array. But what if we loop as follows?
// loop 1
int* p = first;
for (int i=0; i<6; ++i)
std::cout << *p++; // 012345