Structure offset

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • puneetsardana88
    New Member
    • Aug 2009
    • 57

    Structure offset

    Hi

    I want to find offset of structure elements

    Code:
    struct
    {
      char a;
      int b;
      char c;
    }example;
    Code (which i found on books and internet) to find offset is

    Code:
    unsigned int offset;
    offset = (unsigned int)(&(((example *)(0))->b));
    I am not able to understand the above code. What is significance of 0 here? The above code is also not portable also. I do not wish to use offsetof right now. Please help me in solution and explanation as well.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    In this case 0 is being used as a pointer value ((example *)(0)) casts 0 to a pointer to example and then uses that to calculate the offset of b with-in example.

    In what way do you mean this code isn't portable?

    Comment

    • puneetsardana88
      New Member
      • Aug 2009
      • 57

      #3
      I have got the above from Internet. The above is also giving error. Can you elaborate more on this with detailed explanation?

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Refer to offsetof in stddef.h. This is the portable way to find the offset of a structure member.

        The code you quoted in the original post is a common way that offsetof is implemented.

        Comment

        Working...