offsets in structures.
Lambert Meertens
lambert at mcvax.UUCP
Sat Oct 13 20:32:32 AEST 1984
>
>That's a broken compiler. "(struct foo *)0" is of type "pointer to 'struct
>foo'", so adding 1 to it should make it point to the "next" object of type
>"struct foo".
In general, we can hope to find the `array offset' of a struct by
(int)((struct foo*)N+1) - (int)(struct foo*)N
If N = 0, this can be simplified to (int)((struct foo*)0+1). But
there is something special about casting 0 to a pointer: the
result does not point, so the notion of `next object pointed to'
is ill defined. Now what if N != 0? As far as I can see, it is
impossible to *deduce* from K&R that the result is not simply 1.
Assume, for example, a compiler that ensures that values whose
size in bytes is S are always aligned on a multiple of P(S),
where P(S) is a power of two that is at least S. This is,
admittedly, silly, but not forbidden. Now the internal addresses
of S-sized values are all of the form N*P(S), and the code could
then use N as the internal representation of the pointer. The
code for ++ is then simply: add 1 to the integer representing the
pointer. For pointer following, the code should multiply the
pointer N by P(S), where S is the size of the type of objects
pointed to (which looks silly but might be cheap on the
hardware). Casts to int are now supercheap: internally they are
the identity function. The above expression evaluates then to 1.
With this scheme, one cannot guarantee that
(int)(struct foo*)p = (int)(struct bar*)p
but I do not see how this identity would follow from the C
scriptures.
Lambert Meertens
...!{seismo,philabs,decvax}!lambert at mcvax.UUCP
CWI (Centre for Mathematics and Computer Science), Amsterdam
--
Lambert Meertens
...!{seismo,philabs,decvax}!lambert at mcvax.UUCP
CWI (Centre for Mathematics and Computer Science), Amsterdam
More information about the Comp.lang.c
mailing list