Afficher un message
Vieux 06/02/2008, 01h43   #12
A. Sinan Unur
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Neatest way to get the end pointer?

vippstar@gmail.com wrote in
news:a6def63a-34ea-4248-a6d4-0c13e642e59b@1g2000hsl.googlegroups.com:

> On Feb 6, 2:08 am, Keith Thompson <ks...@mib.org> wrote:
>> vipps...@gmail.com writes:
>> > On Feb 6, 12:40 am, "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, 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.
> Correct me if I am wrong, but I have also seen comments in GNU code
> like this:
> --
> /* ANSI C violation */
> char * s = p - 1;
> --
> Where p points to the start of a string passed. 's' is never
> dereferenced, only used for comparing purposes (while(p > s) or
> something similar)


That is different, though. Pointing one past the end of the array is
valid whereas pointing oen before the start of the array is not.

http://www.open-std.org/jtc1/sc22/wg...docs/n1124.pdf

§6.5.6, page 83

Moreover, if the expression P points to the last
element of an array object, the expression (P)+1 points one past the
last element of the array object, and if the expression Q points one
past the last element of an array object, the expression (Q)-1 points to
the last element of the array object. If both the pointer operand and
the result point to elements of the same array object, or one past the
last element of the array object, the evaluation shall not produce an
overflow; otherwise, the behavior is undefined. If the result points one
past the last element of the array object, it shall not be used as the
operand of a unary * operator that is evaluated.


Sinan


--
A. Sinan Unur <1usa@llenroc.ude.invalid>
(remove .invalid and reverse each component for email address)
clpmisc guidelines: <URL:http://www.rehabitation.com/clpmisc.shtml>

  Réponse avec citation
 
Page generated in 0,06775 seconds with 9 queries