内存对齐(C语言问题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013241673/article/details/79690943

牛客网试题:传送门

//在x86系统下,sizeof如下结构体的值是多少?
struct{ 
char a[10];
int b;
short c[3];
}

解析:

struct{ 
char a[10];  //10字节,补齐以后占12字节
int b;       //4字节
short c[3];  //6字节,补齐后占8字节
}            //总共:12+4+8 = 24

图示内存对齐:
图示

类似题目:

typedef struct list_t{
struct list_t *next;
struct list_t *prev;
char data[0];
}list_t;

参考:传送门

#

struct MyStruct
{
    int i;
    char c;
    struct InnerStruct
    {
        int i;
        long l;
        double d;
        char c;
    } innerStruct;
};
union MyUnion
{
    int i;
    char c;
};
int main()
{
   printf("%d, %d", sizeof(MyStruct), sizeof(MyUnion));
}

1、关于结构体大小问题
遵循两条原则:
一、结构体变量中成员的偏移量必须是成员(基本数据类型)大小的整数倍;

什么是偏移量?结构体名代表结构体起始地址,结构体成员的首地址都是构体起始地址 + 偏移地址

二、结构体大小必须是所有成员大小的整数倍。
三、结构体中如果有结构体,把内部结构体打开即可,遵守上述规则一二
1、关于共用体大小问题
共用体大小与其中成员最大大小一致

所以,上题答案:32,4

猜你喜欢

转载自blog.csdn.net/u013241673/article/details/79690943