Page 1 of 1

stddef.h offsetof

Posted: Fri Jun 02, 2006 7:15 am
by Neo
The following macro is defined in stddef.h

Code: Select all

#define offsetof(s,memb) ((size_t)((char *)&((s *)0)->memb-(char *)0))
Couldn't this be replaced with the following

Code: Select all

#define offsetof(s,memb) ((size_t)((char *)&((s *)0)->memb))
// no - (*char *)0

Re:stddef.h offsetof

Posted: Fri Jun 02, 2006 7:29 am
by Ytinasni
This will work on any compiler where

1) the NULL pointer is the bit pattern of all zeroes, and
2) casting a pointer to a size_t gives the same bit representation as the pointer

The C standard requires neither of those to be true, AFAIK.

Having said that, those are both true for most, if not all, compilers targetting x86 and AMD64, as well as those for most other architectures.

In conclusion, you might be able to do that, but its a bad idea if you want your code to be portable to other compilers and/or architectures.

Re:stddef.h offsetof

Posted: Fri Jun 02, 2006 7:54 am
by Solar
Ytinasni wrote: The C standard requires neither of those to be true, AFAIK.
Correct.

Re:stddef.h offsetof

Posted: Fri Jun 09, 2006 5:53 am
by Neo
I am seeing the following lint warning with this which I think is caused by the offsetof().
Is there anything that can be done to overcome this in the code (other than adding a lint comment that is).
    getRg(offsetof(LAPI_RS, medPrm)) )
svcPrm.cpp 33 Warning 413: Likely use of null pointer 'unknown-name' in left argument to operator '->' [Reference: file svcPrm.cpp: line 33]
Where LAPI_RS is a struct and medPrm a member in it.
Any ideas would be greatly appreciated.

Re:stddef.h offsetof

Posted: Mon Jun 26, 2006 9:20 am
by Pype.Clicker
The 'offsetof()' thing make uses of null pointer expressions (and pretty on purpose).

Now, i see nothing that could prevent you of using any kind of symbol instead of NULL (e.g. &((_struct*)main)->_field could do the trick as well), provided that you find a suitable symbol (void* most preferably to avoid type casting warnings)...