簡體   English   中英

C90中的可變長度結構

[英]variable length structures in C90

GNU C中允許零長度數組,因此可以進行初始化

struct line {
       int length;
       char contents[0];
     };

     struct line *thisline = (struct line *)
       malloc (sizeof (struct line) + this_length);
     thisline->length = this_length;

注意:我在這里指的是這個頁面: http//gcc.gnu.org/onlinedocs/gcc/Zero-Length.html (提供C中可變長度結構的基本介紹)

它繼續說:“在ISO C90中,你必須給內容一個長度為1,這意味着你要浪費空間或使參數復雜化為malloc。”

那是什么意思? 有人可以舉例說明如何在C90中初始化變長結構以幫助理解嗎?

如果你真的必須使用c90,那么C FAQ將在問題2.6中涵蓋:

struct name {
int namelen;
char namestr[1];
};

struct name *ret =
    malloc(sizeof(struct name)-1 + strlen(newname)+1);
            /* -1 for initial [1]; +1 for \0 */

雖然FAQ確實說:

目前尚不清楚它是合法的還是便攜的,但它很受歡迎。 該技術的實現可能看起來像這樣。

盡管gcc文檔基本上表示它們支持它,但在C99中,FAQ表示他們添加了靈活的數組成員,我將在第6.7.2.1結構和聯合說明符中介紹的答案中介紹,並且有以下示例,與C90不同示例不需要特殊的數學來計算數組的大小:

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

關於尺寸計算復雜性的評論涉及C與沒有柔性陣列成員支持(即C90與C99)的基本區別。 在結構中使用單數元素數組時,該元素對sizeof()類型有貢獻。 因此,用於真正靈活數組的靈活大小計算將不起作用:

在C90:

struct name 
{
    int namelen;
    char namestr[1]; // contributes 1 + potential padding to sizeof(name)
}; 

// using "the one" [1] as our terminator
struct name *p = malloc(sizeof(name) + strlen(str)) 

而在C99中有一個靈活的成員

struct name 
{
    int namelen;
    char namestr[]; // contributes no definitive value to sizeof(name)
}; 

// specifying space for our terminator, since [] gives us nothing.
struct name *p = malloc(sizeof(name) + strlen(str) + 1)

如果你想知道關於沒有空間貢獻的評論,

C99§6.7.2.1結構和聯盟規范

18作為一種特殊情況,具有多個命名成員的結構的最后一個元素可能具有不完整的數組類型; 這被稱為靈活的陣列成員。 在大多數情況下,將忽略靈活數組成員。 特別地,結構的尺寸好像省略了柔性陣列構件,除了它可以具有比省略意味着更多的拖尾填充。 ....

C90沒有這樣的細節,因此必須以不同的方式分配結構(並且可以說是未指定的方式,如果不是完全未定義的話)。

暫無
暫無

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

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