On Wed, 30 Jun 2004 11:05:40 +0200, Bernd Petrovitsch <bernd@firmix.at> wrote: > On Mit, 2004-06-30 at 10:51, Anupam Kapoor wrote: > > On Wed, 30 Jun 2004 11:38:47 +0300 (IDT), Nir Tzachar > > <tzachar@cs.bgu.ac.il> wrote: > [...] > > > > offsetof is similar: > > > > > > > > <from include/linux/stddef.h> > > > > 12 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) > > > > > > well, lets say you have a structure defined like this: > > > struct foo { > > > int a; > > > int b; > > > int c; > > > char d; > > > }; > > > > > > to get the offset of member c in this struct, we need to size of all > > > members which come b4 c: offset_of_c = sizeof(a)+sizeof(b) . > > no, this is not correct. the compilers are free to add padding to meet > > alignment requirements of a given platform. > > While this is true, ... > > > > however, a more generic and _much_ better way: > > > lets say you had a pointer to a struct foo (foo_ptr), so you can get the > > > offset like this: > > > > > > offset_of_c = &foo_ptr->c - foo_ptr > > > > > > the macro actually saves the subtraction, by letting the compiler think > > > that foo_ptr is 0 ((TYPE *)0) (located at start of memory). > > the assumption here is that null is repersented as a bunch of zeros on > > a platform. if that is not the case, you will get strange results. > > No. A (so-called) null-pointer has two different representations - one > in the C-source (this is 0, '\0', (void *)0, etc.) and one at run-time > in the memory, which is not specified in the C standard. correct. > It is the compilers job to "convert" between these two representations > when it makes sense. > But if the run-time representation is not "all buts are zero" you will > get interesting results after a "memset(p, 0, sizeof(p)", but not for > the above (since the compiler has to - at least virtually - convert at > the right place). indeed. and you will have problem with the above definition in that case. and that's exactly what i am trying to say. > And I do not know if there is any hardware on this planet where the > run-time representation is not "all bits are 0". googling for "non zero representation of NULL" reveals the following enlightning thread on c.l.c http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=422%40minya.UUCP&rnum=5&prev=/groups%3Fq%3Dnon%2520zero%2520representation%2520of%2520NULL%2520group%253Acomp.lang.c.*%26num%3D100%26hl%3Den%26lr%3D%26ie%3DUTF-8%26sa%3DN%26tab%3Dwg kind regards anupam > > Bernd > -- > Firmix Software GmbH http://www.firmix.at/ > mobil: +43 664 4416156 fax: +43 1 7890849-55 > Embedded Linux Development and Services > > -- Kernelnewbies: Help each other learn about the Linux kernel. Archive: http://mail.nl.linux.org/kernelnewbies/ FAQ: http://kernelnewbies.org/faq/