简体   繁体   English

C中sizeof运算符的行为

[英]Behaviour of sizeof operator in C

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. 据我所知,该结构包含一个大小为4的整数变量和一个大小为1的char变量,因此结构a的大小应该为5.但是结构的大小为8。我使用的是Visual C ++编译器。 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. 具有以4字节字对齐开始的数据结构(在具有4字节总线和处理器的CPU上)在围绕存储器以及RAM和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. 这里,编译器在两个成员之间(或之后)插入3个虚拟字节。

You can handle the alignment with #pragma directive. 您可以使用#pragma指令处理对齐。

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. 虽然y只是一个字符,但请注意z是一个完整的4个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM