1、结构体
struct sdshdr {
// buf 中已占用空间的长度
int len;
// buf 中剩余可用空间的长度
int free;
// 数据空间
char buf[];
};
2、怎么理解“struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));”?
源码中经常出现这句话:
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
例如:
/*
* 返回 sds 实际保存的字符串的长度
*
* T = O(1)
*/
static inline size_t sdslen(const sds s) {
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
return sh->len;
}
解释可以看:https://tonybai.com/2013/03/07/struct-hack-in-c/和https://yisaer.github.io/2017/05/07/Redis1/