簡體   English   中英

char指針與char數組不同嗎?

[英]char pointer not the same to char array?

閱讀Redis源代碼

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

我發現char buf[]不能用char *buf代替,因為char* buf會增加struct的大小。

但是我不明白為什么,有人會對此有所啟發嗎?


編輯 :我已經在我的x86_64 Ubuntu(3.2.0-23-generic)和gcc 4.6.3上對其進行了測試,如下所示:

printf(“ sdshdr len =%zu \\ n”,sizeof(struct sdshdr));

使用char buf[] ,通過char *buf輸出sdshdr len = 8sdshdr len = 16

聲明buf成員的方法是利用稱為柔性數組的C99功能,主要優點是可以在結構內部使用可變長度數組(如功能) 因為聲明的buf沒有大小,所以它不占用空間,直到在動態分配sdshdr *結構時顯式分配它為止。

它比使用char *更有效,因為如果bufchar *,我們將必須執行兩個動態分配,首先是對結構sdshdr * ,然后是buf指針本身將需要額外的空間。 這是更干凈的,因為作為一個單元的分配成功或失敗,並且清理更簡單,因為只需要一個free 我們還獲得了數據的局部性,因為整個結構被分配在一個塊中,並且不需要單獨的解除引用來訪問buf

6.7.2.1節中的C99標准草案有一個很好的示例,展示了如何使用此功能:

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).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM