在redis中有一个叫做sdahdr
的结构:
struct sdahdr
{
int len;
int free;
char buf[];
}
为什么不使用 char *buf
而不是 sizeof(sdahdr) == 8
而不是 12?
最佳答案
char buf[]
是字符串的占位符。由于字符串的最大长度在编译时未知,因此该结构为其保留了名称,因此可以对其进行适当的寻址。
在运行时分配内存时,分配必须包括字符串的长度加上结构的大小,然后可以通过数组传递带有字符串的结构。
char *s = "test";
struct sdahdr *p = malloc(sizeof(struct sdahdr)+strlen(s)+1);
strcpy(p->buf, s);
关于c - 为什么在 redis 的 sdahdr 结构中使用 char buf[] 而不是 char *buf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20443099/