2011-07-20 26 views
3

可能重複:
zero length arrays爲什麼字符名稱[0]?

最近,我一直在讀的FUSE源代碼和dirent struct定義如下:

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

誰能解釋一下name[0]是什麼意思?它是爲了什麼?用於填充和對齊?

+2

許多重複: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 –

回答

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 
+0

只是一個警告:0長度數組在C/C++中實際上是非法的,它們只被一些編譯器支持作爲它們自己的擴展。 – KillianDS

+0

是的,你是對的,保險絲的代碼也是這樣的,非常感謝。保險絲源代碼:\t struct fuse_dirent * dirent =(struct fuse_dirent *)buf; \t dirent-> ino = stbuf-> st_ino; \t dirent-> off = off; \t dirent-> namelen = namelen; \t dirent-> type =(stbuf-> st_mode&0170000)>> 12; \t strncpy(dirent-> name,name,namelen); – John

相關問題