arijit_rebaca
asked on
Without using sizeof how do i calculte structure size
Hi,
I have one structure having two int and a char. how do i calculate size of the structure?
thanks,
santanu
I have one structure having two int and a char. how do i calculate size of the structure?
thanks,
santanu
sizeof is the easiest way :
typedef struct Test {
int i;
char c;
} Test;
sizeof(Test);
Other methods will not be reliable due to padding that might be added to the struct.
typedef struct Test {
int i;
char c;
} Test;
sizeof(Test);
Other methods will not be reliable due to padding that might be added to the struct.
Any reason you don't want to use sizeof ?
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
>> (char *)(ptr + 1)
Hehe ... that's cheating lol ... But true : sizeof is not used explicitly.
Hehe ... that's cheating lol ... But true : sizeof is not used explicitly.
>>Hehe ... that's cheating lol ... But true : sizeof is not used explicitly.
:-)
And, one would not of course want to have a struct larger than ptrdiff_t, and, I'm not so sure about using 'u' either - still I reckon it's the kind of thing that someone's got in mind here.
:-)
And, one would not of course want to have a struct larger than ptrdiff_t, and, I'm not so sure about using 'u' either - still I reckon it's the kind of thing that someone's got in mind here.
>> still I reckon it's the kind of thing that someone's got in mind here.
There's a good chance of that :)
There's a good chance of that :)
The size of these is platform dependent (their size isn't defined in the standard)
>> how do i calculate size of the structure?
At best you can approximate it, by adding together the (assumed) size of the types it aggregates but structs can also contain padding and unless you also know how this has been implemented you'll not necessarily get the right result. In other words the sum of the parts might be less than the whole.