3

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?

Community
  • 1
  • 1
John
  • 39
  • 2
  • 2
    Many duplicates: http://stackoverflow.com/questions/4690718/zero-length-arrays ; http://stackoverflow.com/questions/4255193/declaring-zero-size-vector ; http://stackoverflow.com/questions/627364/zero-length-arrays-vs-pointers – Kiril Kirov Jul 20 '11 at 08:22

2 Answers2

0

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.

Simone
  • 11,655
  • 1
  • 30
  • 43
0

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
Jim Buck
  • 20,482
  • 11
  • 57
  • 74
  • Just a warning: 0-length arrays are actually illegal in C/C++, they are only supported by some compilers as their own extension. – KillianDS Jul 20 '11 at 08:57
  • yes,you're right,the code of fuse is also like that,Thank you very much.the fuse source code: 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 Jul 20 '11 at 09:40