+ 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, 05: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, 09:15

      advertising

        
       

  3. #3
    FvM
    FvM is offline
    Super Moderator
    Points: 170,895, Level: 98
    Awards:
    1st Helpful Member

    Join Date
    Jan 2008
    Location
    Bochum, Germany
    Posts
    27,167
    Helped
    8419 / 8419
    Points
    170,895
    Level
    98

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

    An additional reply to a closed thread How to calculate size of structure without using sizeof() operator?

    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.



+ Post New Thread
Please login