Why char name[0]?

3

可能是重复问题:
零长度数组

最近,我一直在阅读FUSE源代码,dirent结构体定义如下:

struct fuse_dirent
{
    __u64 ino;
    __u64 off;
    __u32 namelen;
    __u32 type;
    char name[0];
}

有人能解释一下这里的name[0]是什么意思吗?它有什么作用?是用于填充和对齐吗?


2
许多重复:https://dev59.com/Sm445IYBdhLWcg3w0NSu; https://dev59.com/4lLTa4cB1Zd3GeqPXRtf; https://dev59.com/cnRB5IYBdhLWcg3wbGtB - Kiril Kirov
2个回答

0

我在微软的代码中看到过这种“模式”,通常是当对象中的结构体大小事先不知道时。

你不会用通常的方式分配它,但你可以做一些类似于:

struct fuse_dirent* data = malloc(sizeof(fuse_dirent) + ... );

然后您可以通过访问name成员来访问额外的数据。

当然,这种做法不安全,所以您必须格外小心。


0

当分配此结构时,还将在末尾分配一些额外的空间以存储字符串。这样,可以通过fuse_dirent::name访问该字符串,就像它是一个“真正的”char *类型一样。之所以是[0],是为了不在fuse_direct“头”中分配任何额外的空间。

例如:

fuse_dirent *d = malloc(sizeof(fuse_dirent) + 3);
strcpy(d->name, "hi");
printf(d->name); // will print "hi" to the console

仅供提醒:在 C/C++ 中,0长度数组实际上是非法的,它们只被一些编译器作为其自己的扩展所支持。 - KillianDS
是的,你说得对,fuse的代码也是这样的。非常感谢。fuse源代码如下:struct fuse_dirent dirent = (struct fuse_dirent)buf; dirent->ino = stbuf->st_ino; dirent->off = off; dirent->namelen = namelen; dirent->type = (stbuf->st_mode & 0170000) >> 12; strncpy(dirent->name,name,namelen); - John

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接