日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

C99灵活数组

發布時間:2025/7/14 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C99灵活数组 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

最近在研究redis源碼 ,其中SDS里面的2個函數給我整懵逼了 (redis源碼是C99標準寫的)

如下

#define __SDS_H#define SDS_MAX_PREALLOC (1024*1024)#include <sys/types.h> #include <stdarg.h>typedef char *sds;struct sdshdr {unsigned int len;unsigned int free;char buf[]; }; //static inline size_t sdslen(const sds s) {struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));return sh->len; }static inline size_t sdsavail(const sds s) {struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));return sh->free; }

這個

s-(sizeof(struct sdshdr)

我愣是沒看出來到底等于多少, 原來就是等于2個無符號int相加的值 .

char buf[]; 這個是不占用內存的

這玩意稱為[靈活數組]

靈活數組是添加到C99新特性,稱之為incompleted type,不完全類型,俗稱零數組(zero array),查詢了資料,做了實驗,做個筆記

// // main.c // xpro // // Created by admin on 2018/4/20. // Copyright ? 2018年 admin. All rights reserved. // /**zero array 的代碼示例*/ #include <stdio.h>struct sdshdr {unsigned int len;unsigned int free;char buf[]; };int main(int argc, const char * argv[]) {printf("%ld\n",sizeof(struct sdshdr));const char s[2] = {'1','2'};struct sdshdr *p_sdshdr1;p_sdshdr1 = (struct sdshdr *)malloc(sizeof(unsigned int)*2 + 3);p_sdshdr1->buf[0] = 'a';p_sdshdr1->buf[1] = 'b';p_sdshdr1->buf[2] = '\0';printf("%s\n",p_sdshdr1->buf);return 0; }

運行結果:

8 ab

?

轉載于:https://my.oschina.net/u/2338224/blog/1798662

總結

以上是生活随笔為你收集整理的C99灵活数组的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。