判断结构体变量所占字节数

规则

1,结构体总长度一定是最长字节数的整数倍,double除外,若出现double还是除它之外的最大类型的字节数的整数倍,double还是按8字节算

2,每个成员偏移量一定是改成员长度的整数倍

eg


#include <stdio.h>

struct student
{
    char name[20];
    int a;
    short b;
};

int main()
{
    printf("%d\n", sizeof(struct student));
    return 0;
}

 

嵌套结构体所占字节数示例

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct AA
{
    int a;
    char b;
};
struct student
{
    short c;
    struct AA aa;

    char sex;
    
};

int main()
{
    printf("%d\n", sizeof(struct student));
 
    return 0;
}

说明:

1,struct AA aa,占8个字节; 然后将其整体带入struct student{....}结构体中, short 补两个字节 4+8+1=13, 需要再补三个字节使其为4的倍数

猜你喜欢

转载自blog.csdn.net/weixin_42720316/article/details/81275483
今日推荐