dayoushen
V2EX  ›  问与答

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

  •  
  •   dayoushen · Jul 23, 2020 · 1937 views
    This topic created in 2121 days ago, the information mentioned may be changed or developed.
    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 replies    2020-07-24 07:36:55 +08:00
    pocarisweat
        1
    pocarisweat  
       Jul 23, 2020   ❤️ 3
    这是 c99 的新语法,只能放在最后,多分配出来的内存就可以当作这个数组的内容。char buf[0]意思差不多
    linvon
        2
    linvon  
       Jul 23, 2020   ❤️ 2
    搜索 柔性数组
    dayoushen
        3
    dayoushen  
    OP
       Jul 23, 2020
    谢 1,2 楼,懂了。
    wnpllrzodiac
        4
    wnpllrzodiac  
       Jul 24, 2020 via Android
    老的书写的东西都不对了,尴尬。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5171 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 75ms · UTC 03:57 · PVG 11:57 · LAX 20:57 · JFK 23:57
    ♥ Do have faith in what you're doing.