c++ - 固定宽度结构 C++

标签 c++ c struct

我用以下代码创建了一个结构:

struct d_entry{
   bool _free;
   char name[10];
   bool _dir;
   time_t _cDate;
   unsigned short _cluster;
   char reserved[6];
   unsigned int _size;      
};

我需要我的结构是 32 字节的固定大小。根据我的电脑,以下类型(在结构之外)具有以下大小。

sizeof(bool) = 1 byte
sizeof(char) = 1 byte   
sizeof(time_t) = 8 bytes   
sizeof(short) = 2 bytes  
sizeof(int) - 4 bytes

当我运行任何 d_entry 的大小时,大小为 40 字节。由于某种原因,time_t 和 long 类型被解释为 16 个字节。我一直无法解决这种情况。

最佳答案

您遇到了填充和对齐问题。不同的类型有不同的要求。您可以使用特定于编译器的 pragma 来打包您的成员并解决此问题:

#include <iostream>

struct foo{
   bool _free;
   char name[10];
   bool _dir;
   time_t _cDate;
   unsigned short _cluster;
   char reserved[6];
   unsigned int _size;      
};

#pragma pack(1)
struct bar{
   bool _free;
   char name[10];
   bool _dir;
   time_t _cDate;
   unsigned short _cluster;
   char reserved[6];
   unsigned int _size;      
};

int main()
{
    std::cout << sizeof(foo) << std::endl;
    std::cout << sizeof(bar) << std::endl;

    return 0;
}

这给出了 foo 的大小为 40(正如你所得到的),而 bar 的大小为 32(如你所期望的)。 See on Coliru

关于c++ - 固定宽度结构 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914898/

相关文章:

c - 通过返回的指针访问函数静态结构时出现段错误

c - 头文件中的结构

c++ - 从字符串中替换字符

c - ld : symbol(s) not found for architecture x86_64 (libusb)

c++ - 如何在C/C++中从数组末尾开始复制数据

c - 如何修复c中的 'access past the end of a local variable'

c - 将结构数组传递给函数作为输入

c++ - 为什么使用 memset() 初始化 sigint 变量有助于防止段错误?

c++ - 如何调用破坏函数?

c++ - 在基类和派生类中重载运算符