簡體   English   中英

C中sizeof運算符的行為

[英]Behaviour of sizeof operator in C

我的代碼變得異常,如下所示

#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;
}

對於這段代碼,我得到了輸出:

4 1 8

據我所知,該結構包含一個大小為4的整數變量和一個大小為1的char變量,因此結構a的大小應該為5.但是結構的大小為8。我使用的是Visual C ++編譯器。 為什么會這樣?

它被稱為結構填充

具有以4字節字對齊開始的數據結構(在具有4字節總線和處理器的CPU上)在圍繞存儲器以及RAM和CPU之間移動數據時效率更高。

您通常可以使用編譯器選項和/或編譯指示關閉它,這樣做的具體細節取決於您的特定編譯器。

希望這可以幫助。

編譯器插入填充以用於優化和對齊目的。 這里,編譯器在兩個成員之間(或之后)插入3個虛擬字節。

您可以使用#pragma指令處理對齊。

主要是為了說明這個填充實際上是如何工作的,我已經修改了你的程序了一點。

#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;
}

請注意,我在結構中添加了第三個元素。 當我運行這個程序時,我得到:

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$

下面突出顯示了填充的部分內容。

address of str.y = 0x7fffc962e074
address of str.z = 0x7fffc962e078

雖然y只是一個字符,但請注意z是一個完整的4個字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM