Wednesday, December 16, 2009

Finding Parent Structure's base address from a inner element

Problem:

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 :(

2 comments:

  1. find more details from below
    http://rxwen.blogspot.com/search/label/c%2B%2B

    Venkat

    ReplyDelete
  2. detailed explanation found now

    http://barrgroup.com/comment/14

    ReplyDelete