C语言柔性数组

C语言柔性数组

​ 在阅读redis源码的时候遇到C语言的柔性数组的用法,之前有接触过但是没有深入了解,今天在网上查阅相关资料和写一些小的示例记录下C语言柔性数组的用法和特性。

Redis在sds类型定义中提到了下列的用法,其中每个结构体的最后一个成员char buf[] 即为柔性字数组的用法。下面这种使用方法,通过使用柔性数组,达到了sds类型的包头(header)与实际数据连续存储的目的,提到sds字符串类型的存储和访问效率。

/* Note: sdshdr5 is never used, we just access the flags byte directly.
 * However is here to document the layout of type 5 SDS strings. */
struct __attribute__ ((__packed__)) sdshdr5 {
    unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
    char buf[];
};
struct __attribute__ ((__packed__)) sdshdr8 {
    uint8_t len; /* used */
    uint8_t alloc; /* excluding the header and null terminator */
    unsigned char flags; /* 3 lsb of type, 5 unused bits */
    char buf[];
};

柔性数组

​ 在C99中,为了实现变长的结构体,C语言标准委员会引入了柔性数组的概念。

#include <stdio.h>
#include <sys/types.h>
struct __attribute__ ((__packed__)) sdshdr8 {
    uint8_t len; 
    uint8_t alloc; 
    unsigned char flags; 
    char buf[];			// 柔性数组
};

int main()
{
    // sizeof(sdshdr8):3
 	printf("sizeof(sdshdr8):%u\n", sizeof(sdshdr8));   
}

用法

​ 柔性数组为在结构体的最后声明一个不指定长度或长度为0的数组(该数组的类型可以为任意基本类型)

作用

​ 柔性数组最本质的作用就是将struct结构体类型数据与变长数据达到从内存分布上连续的目的。

限制

​ 1、带有柔性数组的结构体中必须有至少一个其他类型的成员

​ 2、并且柔性数组必须出现在结构体的最后

特点

​ 1、该柔性数组数组名不占用内存空间,它本质上是一个偏移量,代表一个不可修改的地址常量

​ 2、包含柔性数组成员的struct用malloc ()函数进行内存的动态分配时,可以分配的内存大于结构的大小,以适应柔性数组的预期大小,然后再向多余的内存中存储需要的数据

#include <iostream>

struct test_t
{
    int a;
    char b[];
    test_t()
    {
        a = 0;
    }
};

int main()
{
    test_t* test = (test_t*)malloc(sizeof(test_t) + 100*(sizeof(char)));
    char* a = "456";
    strcpy(test->b, a);
    std::cout << test->a << test->b << std::endl;

}

其他实现struct中变长数组的方法

实现struct中包含变长字符串还有其他很多种方法,其中最常见的就是在struct中声明一个指针的方式,如:

struct test
{
	int a;
	char* p;
};

这种方式与柔性数组相比的最大缺点在于给p分配的内存与struct的内存不连续,存取效率较低,易产生内存碎片。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值