如何找到结构的大小? [英] How do I find the size of a struct?

查看:21
本文介绍了如何找到结构的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct a
{
    char *c;
    char b;
};

sizeof(a) 是什么?

What is sizeof(a)?

推荐答案

#include <stdio.h>

typedef struct { char* c; char b; } a;

int main()
{
    printf("sizeof(a) == %d", sizeof(a));
}

我在 32 位机器上得到sizeof(a) == 8".结构的总大小将取决于包装:在我的情况下,默认包装是 4,所以 'c' 需要 4 个字节,'b' 需要一个字节,留下 3 个填充字节将其带到下一个 4 的倍数: 8. 如果你想改变这个包装,大多数编译器都有改变它的方法,例如,在 MSVC 上:

I get "sizeof(a) == 8", on a 32-bit machine. The total size of the structure will depend on the packing: In my case, the default packing is 4, so 'c' takes 4 bytes, 'b' takes one byte, leaving 3 padding bytes to bring it to the next multiple of 4: 8. If you want to alter this packing, most compilers have a way to alter it, for example, on MSVC:

#pragma pack(1)
typedef struct { char* c; char b; } a;

给出 sizeof(a) == 5.如果你这样做,小心在任何库头之前重置打包!

gives sizeof(a) == 5. If you do this, be careful to reset the packing before any library headers!

这篇关于如何找到结构的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆