sizeof 和 unsigned char 数组错误? (c/c++)

发布于 2025-01-05 00:40:45 字数 683 浏览 1 评论 0原文

我写了这个结构:

struct bmpheader {
    unsigned char magic[2];
    unsigned int fsize;
    unsigned int unused;
    unsigned int pixdata_offset;
    unsigned int headersize;
    unsigned int width;
    unsigned int height;
    unsigned short planes_color;
    unsigned short bpp;
    unsigned int compression;
    unsigned int sizeofpix;
    unsigned int resolutionx;
    unsigned int resolutiony;
    unsigned int colors;
    unsigned int imp_colors;
};

我对 sizeof 函数有疑问。当我数手指时,每次都是 54 字节。 sizeof 函数每次都给我 56。为什么?问题是 unsigned char 数组,当我删除 magic[2] 数组时,sizeof 是 52? sizeof(header.magic) 显示为 2。据我所知 unsigned char 是 1 字节类型?

预先感谢您的回复。

马尔辛

i have written this structure:

struct bmpheader {
    unsigned char magic[2];
    unsigned int fsize;
    unsigned int unused;
    unsigned int pixdata_offset;
    unsigned int headersize;
    unsigned int width;
    unsigned int height;
    unsigned short planes_color;
    unsigned short bpp;
    unsigned int compression;
    unsigned int sizeofpix;
    unsigned int resolutionx;
    unsigned int resolutiony;
    unsigned int colors;
    unsigned int imp_colors;
};

And i have a problem with sizeof function. When im counting on my fingers, its every time 54 bytes for me. sizeof function gives me every time 56. Why? The problem is with unsigned char array, when i remove magic[2] array, sizeof is 52? sizeof(header.magic) is shown as 2. As far i know unsigned char is 1-byte type?

Thanks in advance for responses.

marcin

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

記憶穿過時間隧道 2025-01-12 00:40:45

因为 int (在您的机器上)必须放置在 4 字节地址上,或者放置在 4 字节地址上会更有效。编译器将在 char 数组后面插入两个字节的填充。

Because an int (on your machine) must be, or is more efficient when, placed on a 4-byte address. The compiler will insert two bytes of padding after the char array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文