On 06/12/2011 01:44, tenpointwo wrote:
> On Mon, 05 Dec 2011 09:15:07 -0600, KK6GM wrote:
>
>> I've run into some code that uses this idiom for looping through an
>> array
>>
>> some_type *ptr =&some_type_array[0] - 1;
>>
>> while (*(++ptr) != some_val)
>> ...
>>
>> What I'm wondering is whether forming the pointer (&some_type_array[0] -
>> 1) is legal. I realize that this array is never used to access memory.
>> BTW, in the subject line I used a -1 index for brevity. I'm assuming
>> both forms are either legal or illegal, and it is not the case that one
>> is legal and the other is not.
>
> Someone correct me if I'm wrong, I'm pretty new to C.
>
> First off, in your first line I think it could be
> some_type *ptr = some_type_array-1;
> since some_type_array is equivalent to&some_type_array[0], it's really
> up to you though.
>
> Secondly, I think it is a legal expression because&some_type_array[0] is
> just a pointer to the first element in the array, which is just an
> address.&some_type_array[i]-1 for some i would just give you the hex
> address of&some_type_array[i] - 1*sizeof(some_type).
> For instance if some_type=int, and&int_array[i]=0x00400564. Then
> &int_array[i-1]=0x00400560.
>
> So, to conclude, you can evaluate that expression, but you're not
> guaranteed what it would be since the program will just return the hex
> address 4 bytes before some_type_array[0] and treat it as a pointer to
> some_type.
>
> Have you tried compiling it?
A compiler will probably compile the code but that misses the point.
Compilers will frequently generate code that will exhibit undefined
behaviour. If a compiler rejects code you have an error but if a
compiler accepts code all you know is that the code is syntactically
correct but not whether it is semantically so (i.e. will do what you want)
Now just because you can compute an address does not make it a valid
address. It does not guarantee that the address is even within your
program's data area.
Taking or computing the address of an element before the start of an
array results in undefined behaviour. Even should it happen to work on
the hardware/OS you are using it is still something that you should
never do because one day it will stop working, perhaps catastrophically.
>
> --.