取消字节对齐
在结构体声明当中,加上__attribute__ ((__packed__))关键字,可以让结构体,按照紧凑排列的方式来占用内存,结构体的长度,就是各个变量长度的和。
#include<stdio.h>
#include <stdint.h>
struct node1
{
uint8_t a;
uint16_t b;
uint32_t c;
}__attribute__ ((__packed__));
struct node2
{
uint8_t a;
uint16_t b;
uint32_t c;
};
int main()
{
struct node1 tmp1;
struct node2 tmp2;
printf("紧凑:%ld 非紧凑:%ld\n",sizeof(tmp1),sizeof(tmp2));
return 0;
}
输出结果:
紧凑:7 非紧凑:8
node1采用紧凑排列,1+2+4=7
node2它采用了2字节对齐的方式,2+2+4=8
位域操作
指定变量所占位的个数
#include<stdio.h>
#include <stdint.h>
struct node1
{
uint8_t a:8;
uint16_t b:8;
uint32_t c:8;
}__attribute__ ((__packed__));
struct node2
{
uint8_t a;
uint16_t b;
uint32_t c;
};
int main()
{
struct node1 tmp1;
struct node2 tmp2;
printf("紧凑:%ld 非紧凑:%ld\n",sizeof(tmp1),sizeof(tmp2));
return 0;
}
输出结果:
紧凑:3 非紧凑:8