Void pointers and pointer arithmetic
T. William Wells
bill at twwells.com
Wed Jan 3 18:36:24 AEST 1990
In article <1055 at esatst.yc.estec.nl> arne at yc.estec.nl (Arne Lundberg) writes:
:
: 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));
: }
: ---------------------------------------
This is not legal ANSI C. About the only things you can do with
void * are cast them, assign them, and pass them as function
arguments.
: is it possible to write an ANSI compatible ``offsetof'' macro
: for traditional C compilers?
There is no way to write an offsetof macro that will work on all
compilers. There are a number of ways to write it that will work
on most non-ANSI compilers.
---
Bill { uunet | novavax | ankh | sunvice } !twwells!bill
bill at twwells.com
More information about the Comp.std.c
mailing list