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

Status
Not open for further replies.

agg_mayur

Member level 3
Joined
Feb 25, 2010
Messages
66
Helped
3
Reputation
6
Reaction score
3
Trophy points
1,288
Location
India
Activity points
1,715
Hi All,

How to calculate the 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;
}
 

An additional reply to a closed thread https://www.edaboard.com/threads/203627/

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.
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…