日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

C99灵活数组

發布時間:2025/7/14 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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灵活数组的全部內容,希望文章能夠幫你解決所遇到的問題。

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