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

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

问题描述

 一个结构
{
    字符* C;
    炭B:
};

什么是的sizeof(一)?


解决方案

 的#include<&stdio.h中GT;typedef结构{字符* C;炭B: } 一个;诠释的main()
{
    的printf(的sizeof(A)==%D的sizeof(一));
}

我得到的sizeof(A)== 8,在32位机器上。结构的总规模将取决于包装:在我的情况下,默认的包装是4,所以'C'需要4个字节,'B'需要一个字节,其余3填充字节将其带到4的倍数:8.如果你想改变这种包装,大多数编译器有办法改变它,例如,在MSVC:

 的#pragma包(1)
typedef结构{字符* C;炭B: } 一个;

给出的sizeof(A)== 5.如果你这样做,小心前任何库头的包装重置!

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

What is sizeof(a)?

解决方案

#include <stdio.h>

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

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

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;

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

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

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