簡體   English   中英

出於什么原因,結構中還有3個字節? 可以刪除嗎?

[英]For what reason there are 3 bytes more in structs? Can remove?

struct things {
    char foo[25];
    int bar;
};

struct morethings {
    char morefoo[25];
    int morebar;
    int another;
};

int main() {
    printf("char[25] + int: %d | struct things: %d\n\n", sizeof(char[25]) + sizeof(int), sizeof(struct things));
    printf("char[25] + int + int: %d | struct morethings: %d\n\n", sizeof(char[25]) + sizeof(int) + sizeof(int), sizeof(struct morethings));

    return 0;
}

返回:

char [25] + int:29 | 結構物:32

char [25] + int + int:33 | 結構更多:36

我相信在兩種情況下, sizeof返回應該相同,但是結構始終具有最多3個字節。 由於什么原因發生這種情況?

可以刪除嗎? 這可能會破壞我正在做的工作,即保存在文件結構中。

這取決於您使用的編譯器,您需要類似

#pragma pack(push) 
struct things 
  {
    char foo[25];
    int bar;
  };
#pragma pack(pop). 

檢查這些鏈接以獲取更多信息

  1. GNU編譯器gcc
  2. Microsoft編譯器MSDN

還有一個gcc專用解決方案,它是

struct __attribute__ ((__packed__)) things 
  {
    char foo[25];
    int bar;
  };

另一種方法是將最大的元素或具有更嚴格的對齊約束的元素放在結構中。 嘗試:

struct things
{
    int bar;
    char foo[25];
};

代替

struct things
{
    char foo[25];
    int bar;
};

暫無
暫無

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

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