• C

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
arijit_rebacaAsked:
Who is Participating?
 
peetmCommented:
#include <stdio.h>

int main(void)
{
    struct thing
    {
        int     a;
        char    b;
        float   c;
    };
   
    struct thing t;

    struct thing * ptr = &t;

    printf("%u\n", (char *)(ptr + 1) - (char *)ptr);

    return 0;
}
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> I have one structure having two int and a char.
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.
0
 
Infinity08Commented:
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.
0
Firewall Management 201 with Professor Wool

In this whiteboard video, Professor Wool highlights the challenges, benefits and trade-offs of utilizing zero-touch automation for security policy change management. Watch and Learn!

 
Infinity08Commented:
Any reason you don't want to use sizeof ?
0
 
Infinity08Commented:
>> (char *)(ptr + 1)

Hehe ... that's cheating lol ... But true : sizeof is not used explicitly.
0
 
peetmCommented:
>>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.
0
 
Infinity08Commented:
>> still I reckon it's the kind of thing that someone's got in mind here.

There's a good chance of that :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.