In article <11**********************@j72g2000cwa.googlegroups .com>,
<re*********@symantec.comwrote:
>I have a doubt in the following code:
"dobut" is not used that way in English, but that's a topic that
has been covered in a number of previous threads.
>struct xyz
{
int x;
long l;
float f;
};
int main()
{
struct xyz xy;
unsigned int i = (&xy + 1)- &xy;
printf( "%u \n",i);
return 0;
}
>In the above example &xy cancels each other and the code returns a 1.
>My question is :
I feel this should give the difference in memory addresses as the
answer (say size of struct (with alignments ))
why doesnt the compiler takes into account the type of xy as pointer
and do a pointer addition. Is this behaviour in conformance with the C
standard or am I missing something??????
It is the way that pointer arithmetic is defined.
There is no way in C to get the "memory address" of an object: you can
only get a representation of a pointer to the object. Pointers do not
have to be anything like memory addresses. For example, on DEC's VMS, a
pointer might be the address of a "descriptor" that tells the hardware
information about the type of the object and about the size of the
object, so type-checking and array-bounds checking could be done in
hardware.
Pointer arithmetic is defined by the C standard so that p+1 is
the next object (of the same type) after p. Think of it like
arrays: p[0] is the first object, p[1] is the second object,
p[2] is the third, and so on: you increment the subscript to designate
the next member. In C, pointer arithmetic is the difference
in subscripts, not the difference in memory addresses.
In C, the "difference in subscript of arrays" approach is not just
an analogy for conceptual purposes: C really does define it that way.
p[1] is -defined- as *(p+1) and p[2] is -defined- as *(p+2) and
p[J] is -defined- as *(p+J) . p+J is J objects further on than p,
not J memory locations further on.
--
I was very young in those days, but I was also rather dim.
-- Christopher Priest