0

I have been working with structures in C. I had written a code to find the size of structure. It goes like this.

#include<stdio.h>
struct a
{
    int b;
    char c;
};
int main()
{
    printf("%d\n",sizeof(struct a));
    return 0;
}

Here I expected output to be 5. Because structure size is the sum of sizes of all variables in it and in the program integer takes 4 and character takes 1. But after compiling the program I got output like 8. I am thinking why the output is this and in the thought of the may be different compilers act differently so tried in different compilers. But still the output is same. Then another thought like is compiler may consider char as 4 by converting it into ASCII value. So tried with only keeping the single character in structure like this.

#include<stdio.h>
struct a
{
    char c;
};
int main()
{
    printf("%d\n",sizeof(struct a));
    return 0;
}

Then the output is expected and matched which is 1. Can anyone please explain me my char is considered 4 there and why 1 here?

  • The compiler if enforcing a 4-byte alignment on the sturct -- as it should. In the first case, the contents exceeds 4-bytes -- so the compiler adds another 4-bytes (1 for the `char` + 3-bytes padding) for a total of 8-bytes. In the second case, 1-byte easily fits in 4-bytes -- so that is all that is need by the compiler. Depending on your compiler, you can add `#pragma pack` to cause the additional padding bytes to be discarded. See [#pragma pack effect](https://stackoverflow.com/q/3318410/3422102) – David C. Rankin Dec 25 '21 at 05:55
  • The key term is 'structure padding'. There may be other, earlier questions of which this is a duplicate but I didn't find it (SO search term 'structure padding is:q [c]'). – Jonathan Leffler Dec 25 '21 at 05:57

0 Answers0