Void pointers and pointer arithmetic
Arne Lundberg
arne at yc.estec.nl
Tue Jan 2 23:59:20 AEST 1990
I am trying to write some code that tries to access members in a structure
by knowing the start address and the offset to a particular member element.
The following program shows a small example (the real program does not
hardcode the offsets etc.) Is this program legal in ANSI C, will it
produce the desired result?
The (Non-ANSI) compilers I have tested either gives the value for `a'
three times or complains about ``unknown size for pointer to void''.
It works perfectly well if I change the type of p to be ``char *''.
---------------------------------------
struct x {
int a, b, c;
} x = {
1, 2, 3
};
main()
{
void *p = &x;
printf("a %d\n", *(int *)(p + 0));
printf("b %d\n", *(int *)(p + 4));
printf("c %d\n", *(int *)(p + 8));
}
---------------------------------------
BTW,
is it possible to write an ANSI compatible ``offsetof'' macro
for traditional C compilers? I am now using the XtOffset macro
from the X11/Toolkit but would like to have something that doesn't
require an additional name for the ``pointer to the structure'' type.
Arne Lundberg
European Space Technology Centre, Noordwijk, the Netherlands
arne at yc.estec.nl or ALUNDBER at ESTEC.BITNET
Phone: +31 1719 84865, Fax: +31 1719 12142, Telex: 39098
More information about the Comp.std.c
mailing list