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?
You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.
In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.
For example, when the sizeof operator is executed with integer (int) as a parameter, it always returns the number four to indicate that a variable of integer type occupies four bytes of memory.
The sizeof keyword refers to an operator that works at compile time to report on the size of the storage occupied by a type of the argument passed to it (equivalently, by a variable of that type). That size is returned as a multiple of the size of a char, which on many personal computers is 1 byte (or 8 bits).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With