Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!rbutterworth From: rbutterworth@watmath.UUCP Newsgroups: comp.lang.c Subject: Re: structure element offsets Message-ID: <3810@watmath.UUCP> Date: Fri, 5-Dec-86 14:45:16 EST Article-I.D.: watmath.3810 Posted: Fri Dec 5 14:45:16 1986 Date-Received: Sat, 6-Dec-86 01:04:01 EST References: <1096@spice.cs.cmu.edu> <768@nike.UUCP> <3622@watmath.UUCP> <419@viper.UUCP> Organization: U of Waterloo, Ontario Lines: 40 Keywords: structure, offset > According to K&R all > that is required is that (type *)(long *)x == x. K&R does not require this. In fact it is not true on some machines either with or without the second "*". > There are > some machines in which pointers to different types are unrelated > in format. In other words a cast such as (type1 *)(type2 *)x > will not always give a meaningful answer. True. But I wasn't talking about (type1*), I was talking about (char*). As far as I know, any (type2*) can be cast into a (char*) and back again without harm on any machine. (otherwise how does malloc() work?) And any two (char*) pointers can be subtracted to produce the number of bytes between them. > Because your solution doesn't work all the time either. In casting a pointer to (char*), all the strange formats and sizes of pointers are handled by the compiler. The result is a pointer to the first byte of the data. In subtracting two (char*) pointers, all the strange formats and sizes are handled by the compiler. The result is an integer (type (long), (unsigned), (int), ? it doesn't really matter). Thus ( ((char*)pointer1) - ((char*)(pointer2) ) is a completely portable operation. All knowledge of sizes and internal formats is done by the compiler. To cover all possiblilites, you should also divide the result by (sizeof(char)). So if you know of a compiler where my solution doesn't work, it must violate one of the above two rules. Which one? > however, for good or ill, > C has been defined such that all members-of-structures share the > same name-space. This hasn't been true for many years. Are there still any compilers out there that can't handle this? struct one {int a; int b;}; struct two {float b; float a};