J
Johannes Schaub (litb)
I have some question about this one in C:
int a[3][1];
int *ap = &a[0][0];
I know that in C++ the following is perfectly fine:
int ap1 = *ap;
int ap2 = *(ap + 1);
int ap3 = *(ap + 1 + 1);
That is because the past-the-end pointer "ap + 1" happens to point to an
unrelated integer that just happens to be stored there, and dereferencing it
dereferences that pointer. Adding +1 again adds +1 to *that* pointer which
is a pointer into the second subarray of "a". Which will point to the last
integer that just happens to be at the past-the-end position of the second
subarray.
I know that the following two lines are undefined behavior in C++:
int ap3 = *(ap + 2);
int ap3_secondtry = *(ap + (1 + 1));
That is because it adds 2 to the pointer into an array that only has one
element.
Now my question is - how is the matter in C? Is there some paragraph in the
Standard that allows it? To me, it looks like all but "int ap1 = *ap;" is
undefined behavior in C, because it seems to disallow dereferencing the
past-the-end pointer.
Any help is welcome!
int a[3][1];
int *ap = &a[0][0];
I know that in C++ the following is perfectly fine:
int ap1 = *ap;
int ap2 = *(ap + 1);
int ap3 = *(ap + 1 + 1);
That is because the past-the-end pointer "ap + 1" happens to point to an
unrelated integer that just happens to be stored there, and dereferencing it
dereferences that pointer. Adding +1 again adds +1 to *that* pointer which
is a pointer into the second subarray of "a". Which will point to the last
integer that just happens to be at the past-the-end position of the second
subarray.
I know that the following two lines are undefined behavior in C++:
int ap3 = *(ap + 2);
int ap3_secondtry = *(ap + (1 + 1));
That is because it adds 2 to the pointer into an array that only has one
element.
Now my question is - how is the matter in C? Is there some paragraph in the
Standard that allows it? To me, it looks like all but "int ap1 = *ap;" is
undefined behavior in C, because it seems to disallow dereferencing the
past-the-end pointer.
Any help is welcome!