Afficher un message
Vieux 06/02/2008, 01h41   #11
vippstar@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Neatest way to get the end pointer?

On Feb 6, 2:34 am, Peter Nilsson <ai...@acay.com.au> wrote:
> vipps...@gmail.com wrote:
> > Keith Thompson <ks...@mib.org> wrote:
> > > vipps...@gmail.com writes:
> > > > "Tomás Ó hÉilidhe" <t...@lavabit.com> wrote:
> > > > > I commonly use pointers to iterate thru an array.
> > > > > For example:
> > > > > int my_array[X];
> > > [snip]
> > > > > 1) my_array is an int[X]
> > > > > 2) &my_array is an int(*)[X]
> > > > > 3) &my_array+1 is the address of the non-existant
> > > > > array located after the current one.

>
> > > > And you invoke undefined behavior.

>
> > > No, he doesn't. &my_array+1 is a valid address,

>
> Though it requires a conversion back to int * if used
> as a pointer 'index' compared against an int * iterator.
>
> > > just past the end of my_array. Computing this address
> > > is ok; attempting to dereference it would invoke UB.

>
> > I think that when the result of an expression is a non-
> > valid pointer, the behavior is undefined.

>
> True, but one byte past the end of an array _is_ a valid
> pointer.

Ah I see, thanks a lot.
> > Correct me if I am wrong,

>
> Keith already has.

Hehe, sorry mr Keith for doubting :-P.

However, as you said mr Nilsson, he (the OP) is then dereferencing it,
and invoking undefined behavior.
Also, the whole topic is moot.
if sizeof foo / sizeof *foo gives you the elements of foo, then foo
must be an array.
If it's an array it must be defined as 'foo[X]' or similar.
If X is a constant, foo + X is the last pointer (that is not valid to
dereference), if X is an object, it is still foo + X, however foo is
then a variable length array.
Therefore, there is no need for foo + sizeof foo / sizeof *foo.
  Réponse avec citation
 
Page generated in 0,05912 seconds with 9 queries