-
Macro question
I'm in the middle of dissecting a program, and I've run across a weird macro... I can't seem to figure out what it does:
MACRO (z,w) ( (int) ( &(((z*)0)->w) )
I think w is a member variable of a class or structure.
That means the ((z*)0) has to be a pointer to a class or structure... but how's it work? That's not a dereference, since things are dereferenced with the '*' before the variable name. And why the '0'? This has got to be the weirdest piece of C code I've ever seen.
I know it has to return an int, since that's the final cast. Also, I know it's an address location, because of the &. But what does the ((z*)0) do? Ohh, I'm so confused. C masters, please help!
My guess is that z would be some class type, and that the "&(((z*)0)->w)" is the address of the declaration of w in memory, if that's possible. That really doesn't seem right though!
-
It looks like a perfect way to get NULL-pointer exception, but I am
not sure. Check out /P compiler switch - it allows to see the code
after preprocessor. This helps to understand crazy macros.
-
MACRO (z,w) ( (int) ( &(((z*)0)->w) )
z is a structure(class) name and w is a member
struct z {
//...
type w;
};
and the MACRO returns which byte from the strusture w thakes
if you have en element
z myz;
&myz + MACRO(z, w) will return the address of w in myz
or &(myz.w)
-
Actually, to be insufferably pedantic for a moment, it does nothing of the sort. There's a space between the word MACRO and the opening parenthesis, so it won't be parsed as a macro with arguments, but as a no-argument macro with the replacement text: (z,w) ( (int) ( &(((z*)0)->w) ), which is probably going to result in a syntax error.
-
Thank you!
SeventhStar, you're dead on. The space between the macro and the arguments was my own sloppy fault. Thank you for clearing up that weird piece of code... you've made me a little bit smarter!
-Riskbreaker
-
this macro is usually known as "offsetof"