2013-12-12 149 views
2

source code of Redischar指針與char數組不一樣?

struct sdshdr { 
    int len; 
    int free; 
    char buf[]; 
}; 

我發現char buf[]無法char *buf被取代,在這個意義上,char* buf將增加結構的大小。

但我不明白爲什麼,有人會對此有所瞭解?


編輯:我用gcc 4.6.3測試它在我的Ubuntu x86_64的(3.2.0-23-通用)是這樣的:

的printf(「sdshdr LEN =% zu \ n「,sizeof(struct sdshdr));

char buf[]隨着它輸出sdshdr len = 8sdshdr len = 16char *buf

+2

'字符* buf'不會增加結構的大小。 – moeCake

+0

是的,請參閱我更新的問題。 @moeCake – adamsmith

+0

[%zu是size_t的正確格式說明符](http://stackoverflow.com/questions/940087/whats-the-correct-way-to-use-printf-to-print-a-size-t )這是'sizeof'返回的內容。 –

回答

3

buf成員聲明的方式是利用C99特性靈活的數組,主要優點是獲得use of variable length array like features inside a struct。由於buf被聲明爲沒有大小,因此只有在動態分配struct sdshdr *時才明確分配空間。

它比使用更高效的一個的char *因爲如果buf的char *我們將不得不進行兩個動態分配,首先對結構sdshdr *爲buf,然後再和指針本身需要額外的空間。這是更清潔的,因爲分配成功或失敗作爲一個單元和清理更簡單,因爲只需要一個free。由於整個結構被分配在一個塊中,我們也獲得了數據的局部性,並且不需要單獨的取消引用來訪問buf

6.7.2.1draft C99 standard有一個很好的例子,說明如何使用此功能:

EXAMPLE After the declaration: 

    struct s { int n; double d[]; }; 

the structure struct s has a flexible array member d. A typical way to use this 
is: 

    int m = /* some value */; 
    struct s *p = malloc(sizeof (struct s) + sizeof (double [m])); 

and assuming that the call to malloc succeeds, the object pointed to by p 
behaves, for most purposes, as if p had been declared as: 

    struct { int n; double d[m]; } *p; 

(there are circumstances in which this equivalence is broken; in particular, the 
offsets of member d might not be the same). 
+0

非常感謝您提供更新的答案,這對您有所幫助! – adamsmith