0

I am creating two structs in C that have the same number of variables: 3 integers and 3 chars. When i look at the size of an instance of each of the structs using the sizeof() operator i get two different values. I wonder Why is this happening, here is my code: I tried rearranging the variable with the same result.

typedef struct a
{
int x;
char a;
int y;
char b;
int z;
char c;
}s1;

typedef struct b
{
int x;
int y;
int z;
char a;
char b;
char c;
}s2;

int main()
{
printf("%d %d\r\n", sizeof (s1), sizeof (s2));
return 0;
}

1 Answers1

1

Very simply putting, the processors align the variables based on the word size. The integers in your case are aligned at 4 byte boundaries, so when you interlace your characters and integers, 3 bytes after every character is not utilized. Refer to: https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/

basak
  • 1,909
  • 2
  • 11
  • 7