我正在努力学习如何使用sds函数。我在我的项目文件夹中有代码sds.h和sds.c代码文件,以及我编写、编译和运行的小型探索程序。但是,我很难理解从sds.h和sds.c文件中看到的代码中的一些内容。我不知道为什么它会编译,更不用说工作了。
有关守则是:
typedef char *sds;
struct sdshdr {
int len;
int free;
char buf[];
};
static inline size_t sdslen(const sds s) {
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
return sh->len;
}在sds.c文件中多次调用sdslen()函数,在包含sds.h之后,我甚至可以在自己的程序中使用它。我知道that使sds成为一个仅仅是char指针的类型。静态关键字限制函数的作用域。内联意味着函数在调用时将被编译器粘贴到代码中,而不是使用堆栈和函数调用机制。在我看来,sdslen()函数中的*sh指针在存储在s中的地址之前分配了一个地址大小( struct )内存地址,然后在没有初始化结构中的任何变量的情况下,len成员变量被传回。任何帮助,了解这一点,什么是真正发生的,将不胜感激。
发布于 2013-11-06 18:47:47
我想我想明白了。答案在sds.c文件的另一个函数中:
sds sdsnewlen(const void *init, size_t initlen) {
struct sdshdr *sh;
if (init) {
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
} else {
sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
}
if (sh == NULL) return NULL;
sh->len = initlen;
sh->free = 0;
if (initlen && init)
memcpy(sh->buf, init, initlen);
sh->buf[initlen] = '\0';
return (char*)sh->buf;
}当一个新的sds被sdsnewlen()函数创建并初始化时,动态地为整个结构和c-字符串分配内存,但是c-字符串的地址才会被传回。如果sdslen()是用使用malloc分配的sds变量调用的,而不使用sdsnewlen()函数,则会导致问题。只要使用提供的函数初始化sds变量,那么内存是有效的,成员变量已经初始化,sds变量可以像任何c-字符串一样在printf()中使用。
https://stackoverflow.com/questions/19819527
复制相似问题