柔性数组
在结构体中需要申请一个数组,有两种方法:
1、
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len;
uint8_t alloc;
unsigned char flags;
char* buf; // 使用指针
}
使用这种方法,需要malloc两次,free两次,分别是结构体本身申请一次空间,buff再申请一次空间。另一个效率更高的方法是使用柔性数组:
2、
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len;
uint8_t alloc;
unsigned char flags;
char buf[]; // 柔性数组
}
编译器知道是柔性数组,所以在初始化时数组不占用空间;在使用时只需要malloc一次,free一次就行,使用如下:
s = malloc(sizeof(struct sdshdr8) + 64); // 数组大小为64B
sds = s + sizeof(struct sdshdr8); // sds的地址是数组首地址+偏移量(因为柔性数组不占用空间)
// 使用结构体
free(sds - sizeof(struct sdshdr8)); // 释放空间