0

To find the size of a structure in C

struct student
    {
     char name;
     int age;
     float weight;
    };

main () { int i,j,k,l; struct student s1; i=sizeof(s1.name); j=sizeof(s1.age); k=sizeof(s1.weight); l=sizeof(s1); printf ("\n size of name %d",i); printf ("\n size of age %d",j); printf ("\n size of weight %d",k); printf ("\n size of s1 %d",l);

printf("\n"); }

My output is:

size of name 1 size of age 4 size of weight 4 size of s1 12

But structure size should be the sum of sizes of its members. Why am i getting 12 instead of 9 as size of structure variable s1. Can someone explain what is wrong.

Sudheer
  • 228
  • 1
  • 4
  • 13
  • To find the size of a structure, simply use `sizeof (struct student)`. Incidentally: you need `#include `, `main ()` should be `int main(void)`, and your `\n`s should be at the *end* of each line of output. – Keith Thompson Jul 11 '14 at 23:14

1 Answers1

5

For performance or hardware reasons, fields in structures should be suitably aligned. Read about data structure alignment (details depend upon the target processor and the ABI).

In your example on x86-64/Linux:

struct student {
 char name;
 int age;
 float weight;
};

the field name has no alignment requirement. the field age needs 4 bytes aligned to a multiple of 4 the field weight needs 4 bytes aligned to a multiple of 4

so the overall struct student needs 12 bytes aligned to a multiple of 4

If weight was declared double it would need 8 bytes aligned to a multiple of 8, and the entire structure would need 16 bytes aligned to 8.

BTW, the type of your name field is wrong. Usually names are more than one single char. (My family name needs 13 letters + the terminating null byte, i.e. 14 bytes). Probably you should declare it a pointer char *name; (8 bytes aligned to 8) or an array e.g. char name[16]; (16 bytes aligned to 1 byte).

The GCC compiler provides a nice extension: __alignof__ and relevant type attributes.

If performance or size is important to you, you should put fields in struct in order of decreasing alignment requirements (so usually start with the double fields, then long and pointers, etc...)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547