Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83 (MC840302); site mcvax.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!godot!harvard!seismo!mcvax!lambert From: lambert@mcvax.UUCP (Lambert Meertens) Newsgroups: net.lang.c Subject: Re: offsets in structures. Message-ID: <6084@mcvax.UUCP> Date: Sat, 13-Oct-84 06:32:32 EDT Article-I.D.: mcvax.6084 Posted: Sat Oct 13 06:32:32 1984 Date-Received: Mon, 15-Oct-84 01:38:27 EDT References: <393@orion.UUCP> <6080@mcvax.UUCP> <185@rlgvax.UUCP> Organization: CWI, Amsterdam Lines: 41 > >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@mcvax.UUCP CWI (Centre for Mathematics and Computer Science), Amsterdam -- Lambert Meertens ...!{seismo,philabs,decvax}!lambert@mcvax.UUCP CWI (Centre for Mathematics and Computer Science), Amsterdam