Zero-sized Array

Zero-sized Array

在memcached源码中看到的:

/**
 * Structure for storing items within memcached.
 */
typedef struct _stritem {
    ......
    /* this odd type prevents type-punning issues when we do
     * the little shuffle to save space when not using CAS. */
    union {
        uint64_t cas;
        char end;
    } data[];
    /* if it_flags & ITEM_CAS we have 8 bytes CAS */
    /* then null-terminated key */
    /* then " flags length\r\n" (no terminating null) */
    /* then data with terminating \r\n (no terminating null; it's binary!) */
} item;

以前没有见过,而且用sizeof看,data字段完全不占空间,网上搜了下,做点笔记。

先看个例子,

#include <stdio.h>

int main() {
    int arr[0];
    return 0;
}

这段代码用gcc是可以编译通过的,只有在加入 -pedantic 边缘选项后会警告:

$ gcc -pedantic test.c -o t
test.c: In function ‘main’:
test.c:22:9: warning: ISO C forbids zero-size array ‘arr’ [-pedantic]

gnu 上开头就举了一个Zero Length Array的实用例子:

struct line {
  int length;
  char contents[0];
};

struct line *thisline = (struct line *)
  malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

这个技巧非常有用,contents和结构体内存上相近,读取很快,而且节省一个指针(contents是不占内存的)

因此,上文的这段代码:

union {
    uint64_t cas;
    char end;
} data[];

表示定义一个成员名叫data的zero-length array, 而data的类型是union, 以后可以通过data[i].cas 或 data[i].end来获得内存中数据。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值