Why ?

my code is

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

struct SV
 {
      char name[10];
      int age;
      float mark;
 }s;

int main()
 {
      cout <<sizeof(s);
      return 0;
 }


why output is 20?

Can anyone explain?
Thanks !
Because the size of the data of the structure takes 20 bytes.

What were you expecting??
Dai ca. To my understanding that is because the compiler is lazi. (Someone told me this but I don't know if it's true or not. lolz)

This is because size of this particular data structure is the result of combining the size of it individual members. Plus wasted bytes used by the compiler for alignment purposes if and when the data of the individual members is not of equal size. Like if you try above with just char, int, and float, it will be equal to 12. The compiler will put 3 wasted byte in after char so it can do 4, 8, and 12. O_o I guess it's easier to count in multiples of bytes than not. O_O

I don't know much more then that, but. There is a very good explanation for this on the following site:
http://cprogramming.com/tutorial/size_of_class_object.html
Last edited on
The compiler will add bytes so that the size of the structure is a multiple of a certain number of bits. On x86 it's 32, on x64 it's 64.
char array (10 bytes)
int (4 bytes)
float (4 bytes)
2 bytes of padding
10+4+4+2=20
20/4=5
Why output is 12 if I change the fifth line to
char name; or char *name; (1+4+4=9 != 12)
Remember that the compiler will insert padding bytes until the size is a multiple of 32 bits.
1+4+4+(3 padding bytes)=12

The size of a pointer is the same as the processor mode the system is using, so on a 32-bit system, a pointer is 4 bytes long.
4+4+4+(0 padding bytes)=12
Topic archived. No new replies allowed.