+ Post New Thread
Results 1 to 3 of 3

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

  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?

    •   Alt 

      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;
    }



    •   Alt 

      advertising

        
       

  3. #3
    FvM
    FvM is offline
    Advanced Member level 5
    Points: 139,063, Level: 89
    Achievements:
    7 years registered
    Awards:
    Helpful gold

    Join Date
    Jan 2008
    Location
    Bochum, Germany
    Posts
    21,453
    Helped
    6411 / 6411
    Points
    139,063
    Level
    89

    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