structure element offsets

rbutterworth at watmath.UUCP rbutterworth at watmath.UUCP
Sat Dec 6 05:45:16 AEST 1986


> 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};



More information about the Comp.lang.c mailing list