V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
dayoushen
V2EX  ›  问与答

redis 源码 sds 的结构体使用 c 语言的什么魔法

  •  
  •   dayoushen · 2020-07-23 19:38:15 +08:00 · 1108 次点击
    这是一个创建于 1370 天前的主题,其中的信息可能已经有所发展或是发生改变。
    struct sdshdr {
        long len;
        long free;
        char buf[];
    };
    

    如上,这个 char buf[] 竟然不占内存,在 64 位系统 sizeof(long)=8,sizeof(sdshdr)=16 。问题是这个 buf 为什么不占内存,不能理解为 char * ?然后使用中 sdshdr * newsds = (sdshdr * )malloc(sizeof(sdshdr) + initlen + 1),newsds->buf 又可以操作后面的字符。

    4 条回复    2020-07-24 07:36:55 +08:00
    pocarisweat
        1
    pocarisweat  
       2020-07-23 19:49:41 +08:00   ❤️ 2
    这是 c99 的新语法,只能放在最后,多分配出来的内存就可以当作这个数组的内容。char buf[0]意思差不多
    linvon
        2
    linvon  
       2020-07-23 19:54:32 +08:00   ❤️ 1
    搜索 柔性数组
    dayoushen
        3
    dayoushen  
    OP
       2020-07-23 20:20:51 +08:00
    谢 1,2 楼,懂了。
    wnpllrzodiac
        4
    wnpllrzodiac  
       2020-07-24 07:36:55 +08:00 via Android
    老的书写的东西都不对了,尴尬。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   978 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 21:02 · PVG 05:02 · LAX 14:02 · JFK 17:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.