如何设置结构体所占字节不对齐

其实很简单:

typedef struct
{
    int a;
    char b;
}__attribute__((packed))  data_t;

然后使用 data_t 进行定义结构体变量即可:

例如 :

data_t a;

printf("%d\n",sizeof(a));

结果为:5

#include<stdio.h>
typedef struct
{
    int a;
    char b;
}__attribute__((packed)) data_t;

int main(){
    
    data_t a;

    printf("%d\n",sizeof(a));
    
    return 0;
}

但是如果调换一下位置:

例如:

是不是很奇怪,有知道原因的么?     ^_^

猜你喜欢

转载自blog.csdn.net/farsight_2098/article/details/86627563