Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!twwells!bill From: bill@twwells.com (T. William Wells) Newsgroups: comp.std.c Subject: Re: Void pointers and pointer arithmetic Message-ID: <1990Jan3.073624.14061@twwells.com> Date: 3 Jan 90 07:36:24 GMT References: <1055@esatst.yc.estec.nl> Organization: None, Ft. Lauderdale, FL Lines: 42 In article <1055@esatst.yc.estec.nl> arne@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@twwells.com