+ Post New Thread
Results 1 to 3 of 3
  1. #1
    Member level 3
    Points: 786, Level: 6

    Join Date
    Feb 2010
    Location
    India
    Posts
    67
    Helped
    3 / 3
    Points
    786
    Level
    6

    How to calculate size of structure without using sizeof() operator?

    Hi All,

    How to calculate the size of structure without using sizeof() operator?

    •   Alt25th February 2011, 06:37

      advertising

        
       

  2. #2
    Member level 3
    Points: 786, Level: 6

    Join Date
    Feb 2010
    Location
    India
    Posts
    67
    Helped
    3 / 3
    Points
    786
    Level
    6

    Re: How to calculate size of structure without using sizeof() operator?

    It is done.

    struct point {
    char x;
    int i;
    float f;
    char is;

    }pt;

    int main()
    {
    // struct point pt = {0},
    struct point *ppt;
    *ppt = &pt;
    unsigned char *p1 = 0, *p2 = 0;

    size_t size = 0;

    p1 = (unsigned char*)(ppt);
    p2 = (unsigned char*)(++ppt);
    size = p2 - p1; // size is now 8 bytes (2 longs)
    printf("%d\n",size);
    // same as sizeof(struct point) or sizeof(pt)

    return 0;
    }



    •   Alt25th February 2011, 10:15

      advertising

        
       

  3. #3
    Super Moderator
    Points: 231,438, Level: 100
    Awards:
    1st Helpful Member

    Join Date
    Jan 2008
    Location
    Bochum, Germany
    Posts
    39,951
    Helped
    12203 / 12203
    Points
    231,438
    Level
    100

    Re: How to calculate size of structure without using sizeof() operator?

    An additional reply to a closed thread http://www.edaboard.com/thread203627.html

    Your solution is:
    Code:
    p1 = (unsigned char*)(ppt);
    p2 = (unsigned char*)(++ppt);
    size = p2 - p1; // size is now 8 bytes (2 longs)
    I guess, it has been a homework problem, but it seems pretty useless to me. You can assume, that the compiler will simply apply sizeof() when calculating ++ppt. So what have you won by avoiding an explicite usage of sizeof(), except wasting program space?

    The important point to understand is, that you have to refer to original object definition to know it's size. sizeof() is the straightforward way.



--[[ ]]--