c - 为什么在 redis 的 sdahdr 结构中使用 char buf[] 而不是 char *buf

标签 c redis

在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/

相关文章:

Redis:INCRBY 一个 BigFloat 数字

mongodb - 为什么在什么场景下使用 REST 更好? NoSQL

c - 如何在 Github 上托管的存储库上使用 git_branch_create()?

c - 为什么我的 fscanf 不读取?

c - 系统范围页表

c - OpenGL SOIL 使用纹理颜色绘制整个屏幕

django - 如何为 Django 测试模拟 Redis

redis - 重复的 redis 列表

php - 如何在 Ubuntu 环境中为 XAMPP 启用 Redis 扩展。

C - 拆分字符串