C99灵活数组
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
最近在研究redis源碼 ,其中SDS里面的2個函數(shù)給我整懵逼了 (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[]; 這個是不占用內存的這玩意稱為[靈活數(shù)組]
靈活數(shù)組是添加到C99新特性,稱之為incompleted type,不完全類型,俗稱零數(shù)組(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
總結
- 上一篇: Docker mongodb Docke
- 下一篇: Javascript Symbol 隐匿