I am getting unusual behaviour with my code, which is as follows
#include<stdio.h>
struct a
{
int x;
char y;
};
int main()
{
struct a str;
str.x=2;
str.y='s';
printf("%d %d %d",sizeof(int),sizeof(char),sizeof(str));
getch();
return 0;
}
For this piece of code I am getting the output:
4 1 8
As of my knowledge the structure contains an integer variable of size 4 and a char variable of size 1 thus the size of structure a should be 5. But how come the size of structure is 8.
I am using visual C++ compiler.
Why this behaviour?
It is called Structure Padding
Having data structures that start on 4 byte word alignment (on CPUs with 4 byte buses and processors) is far more efficient when moving data around memory, and between RAM and the CPU.
You can generally switch this off with compiler options and/or pragmas, the specifics of doing so will depend on your specific compiler.
Hope this helps.