Topic: Pointers to non-array objects


Author: "James Kuyper Jr." <kuyper@wizard.net>
Date: Mon, 14 May 2001 22:57:27 GMT
Raw View
[subject changed from "Re: C++0x", which is far too crowded, anyway]

Daniel James wrote:
...
> I don't think there's any need to go beyond "implementation defined" and
> struggle with the kind of verbiage that James Kuyper tells us the C99
> standard has introduced ...
>
> > ... or one is a pointer to one past the end of one array object
> > and the other is a pointer to the start of a different array
> > object that happens to immediately follow the first array object
> > in the address space.
>
> [which is insufficient anyway, because the "other pointer" might be a
> pointer to a non-array object that just "happens to follow...".]

That's not a problem, it's covered by both C99 and C++98:

C99 6.5.6p7: "For the purposes of these operators, a pointer to an
object that is not an element of an array behaves the same as a pointer
to the first element of an array of length one with the
type of the object as its element type."

C++98 5.7p4 says exactly the same thing, except that it shortens "an
object that is not an element of an array" to "a nonarray object".
Unfortunately, those two phrases don't mean exactly the same thing:

 int array[3], single;
 int *p=array;
 int *q=&single;
 int (*r)[3] = array;

The only one of those three pointers which points at an object which is
an element of an array is 'p', so the C99 rule applies to both 'q' and
'r'. The only one of those three pointers which points at an array
object is 'r', so the C98 rule applies to both 'p' and 'q'. It's no
problem with 'p', since applying the rule has the same effect as not
applying it - you could even argue that since 'p' points into an array
object, it counts as pointing at an array object; I won't worry about
that issue.

However, I think the rule was also intended to apply to 'r', which
should be treated as a pointer into the first element of an int[1][3].
In other words, is 'r+1' a valid pointer?  The rules for pointer
addition are defined in 5.7p5 in terms of an array of the pointed-at
object type; if there's no such array, then pointer addition is
undefined. Since 'r' very definitely points at an array object, 5.7p4
doesn't apply, which would otherwise allow us to pretend that it points
at the first element of an array of int[1][3], even though there
actually isn't.
'r+1' is not dereferenceble, of course, but I should for instance be
able to provide (r,r+1) as the range delimeters to a template function
that takes an iterator range.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.research.att.com/~austern/csc/faq.html                ]