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.
The compiler inserts padding for optimization and aligment purposes. Here, the compiler inserts 3 dummy bytes between (or after) your both members.
You can handle the alignment with #pragma
directive.
Mostly to illustrate how this padding actually works, I've amended your program a little.
#include<stdio.h>
struct a
{
int x;
char y;
int z;
};
int main()
{
struct a str;
str.x=2;
str.y='s';
str.z = 13;
printf ( "sizeof(int) = %lu\n", sizeof(int));
printf ( "sizeof(char) = %lu\n", sizeof(char));
printf ( "sizeof(str) = %lu\n", sizeof(str));
printf ( "address of str.x = %p\n", &str.x );
printf ( "address of str.y = %p\n", &str.y );
printf ( "address of str.z = %p\n", &str.z );
return 0;
}
Note that I added a third element to the structure. When I run this program, I get:
amrith@amrith-vbox:~/so$ ./padding
sizeof(int) = 4
sizeof(char) = 1
sizeof(str) = 12
address of str.x = 0x7fffc962e070
address of str.y = 0x7fffc962e074
address of str.z = 0x7fffc962e078
amrith@amrith-vbox:~/so$
The part of this that illustrates padding is highlighted below.
address of str.y = 0x7fffc962e074
address of str.z = 0x7fffc962e078
While y is only one character, note that z is a full 4 bytes along.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.