I have a structure as below
struct School
{
struct {
int sCode;
float elgCode;
} Service;
long variable1;
int variable2;
void (*fp)();
} JNVL;
and I have the address of Service.elgCode i.e JNVL.Service.elgcode now I should find the base address of the parent structure i.e JNVL which I dont have right now.
Solution:
( (struct School *) ( (unsigned long) (&Service.elgCode) - (unsigned long ) & (struct School *) 0)->Service.elgcode))
will get you the base address
Analysis :
L1 (
L2 (struct School *)
L3 (
L4 (unsigned long) (&Service.elgCode)
L5 -
L6 (unsigned long ) & ((struct School *) 0)->Service.elgcode
L7 )
L8 )
So in explanation we are subtracting the address of relative base address which we got through by casting to Zero (L6) from the available address (L4) so we will get the base address of the parent object
We can write macros for the same such that
#define NMEMBEROF(s,f,p) ((s *)((unsigned long)(p) - (unsigned long)&((s *)0)->f))
Black Area: Still I should understand the intention of casting to Zero :(
find more details from below
ReplyDeletehttp://rxwen.blogspot.com/search/label/c%2B%2B
Venkat
detailed explanation found now
ReplyDeletehttp://barrgroup.com/comment/14