Void pointers and pointer arithmetic
Henry Spencer
henry at utzoo.uucp
Wed Jan 3 07:34:08 AEST 1990
In article <1055 at esatst.yc.estec.nl> arne at yc.estec.nl (Arne Lundberg) writes:
>...Is this program legal in ANSI C, will it
>produce the desired result?
No. Pointer arithmetic is not defined for pointer-to-void. It can't be,
since it's not possible to do pointer arithmetic without knowing the size
of the type pointed to.
>BTW,
>is it possible to write an ANSI compatible ``offsetof'' macro
>for traditional C compilers? ...
Sort of. We do this in C News. Here's what we say about it in our
porting-problems document (C News enthusiasts: this will be in the
next patch):
Unfortunately, it is really hard to write a portable version of this.
The implementation we currently use is:
.DS
#define offsetof(type, mem) ((char *)&((type *)NULL)->mem - (char *)NULL)
.DE
The table in \fIrelay/hdrdefs.c\fR
puts invocations of \fIoffsetof\fR in initializers.
This turns out to be a severe stress test for C compilers.
A compilation error in \fIhdrdefs.c\fR is almost certain
to be problems with this macro.
Some compilers,
notably the one in Microport System V Release 2.3,
reject it.
We have heard a report that System V Release 2 on the VAX silently
miscompiles it!
If you have trouble with \fIoffsetof\fR, you might try
this version instead:
.DS
#define offsetof(type, mem) ((int)&((type *)NULL)->mem)
.DE
--
1972: Saturn V #15 flight-ready| Henry Spencer at U of Toronto Zoology
1990: birds nesting in engines | uunet!attcan!utzoo!henry henry at zoo.toronto.edu
More information about the Comp.std.c
mailing list