The question of memory allocation of variables in the structure (In C)

Possible duplicate:
Why is the sizeof sizeof the structure not equal to the sumofofof each member?

#include <stdio.h>

int main(){

struct word1{
 char a;
 int b;
 char c;
};

struct word2{
 char a;
 char b;
 int c;
};

printf("%d\t%d\n", sizeof(int), sizeof(char));   //Output : 4 1
printf("%d\t%d\n", sizeof(struct word1), sizeof(struct word2)); //Output: 12 8
return 0;
}

The code is available in IDEONE .

Why is the size of struct 1 (word1) larger than the size of struct 2 (word2)?

Is this a compiler problem?

+3
source share
2 answers

int, , , char , , char ( char ).

word1 :

0   |1   |2   |3   |4   |5   |6   |7   |8   |9   |10  |11
a   |  (padding)   |b                  |c   |  (padding)

word2 :

0   |1   |2   |3   |4   |5   |6   |7
a   |b   |(padding)|c               
+9

1:

  0    1    2    3    4  
+---------------------+
| a    | Unused       |      4 bytes
+---------------------+

  0    1    2    3    4 
+---------------------+
|       b             |      4 bytes
+---------------------+

  0    1    2    3    4 
+---------------------+ 
| c    | Unused       |      4 bytes
+---------------------+

: 12

2:

  0    1    2    3    4 
+---------------------+
| a   | b   | Unused  |      4 bytes
+---------------------+

  0    1    2    3    4 
+---------------------+
|       c             |      4 bytes
+---------------------+

: 8

P.S: .

+4

Source: https://habr.com/ru/post/1771141/


All Articles