开发者

Why char name[0]? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

zero length arrays

Recently, I've been reading the FUSE source code and the dirent struct is defined as follows:

struct fuse_dirent
{
    __u64 ino;
    __u64 off;
    __u32 namelen;
   开发者_运维知识库 __u32 type;
    char name[0];
}

Can anyone explain what name[0] means here? What is it for? For padding and alignment?


I've seen this "pattern" in Microsoft's code, usually when the struct in object's size is not known a priori.

You don't allocate it with the usual way, but you do something like:

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

then you can access the extra data by accessing name member.

Of course, this practice is not safe, so you have to pay extra attention.


When this structure is allocated, some additional space will also be allocated at the end for storing a string. This way, the string can be accessed through fuse_dirent::name as if it were a "real" char * type. The reason for it being [0] is to not allocate any additional space in the fuse_direct "header".

An example:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜