3 回答

TA貢獻2080條經驗 獲得超4個贊
C ++于1998年首次標準化,因此它早于C中添加了靈活數組成員(C99中的新增功能)。2003年對C ++進行了更正,但是并沒有添加任何相關的新功能。C ++的下一個修訂版(C ++ 0x)仍在開發中,似乎沒有在其中添加靈活的數組成員。

TA貢獻1826條經驗 獲得超6個贊
C ++在結構的末尾不支持C99靈活數組成員,無論是使用空索引符號還是0索引符號(除非特定于供應商的擴展名):
struct blah
{
int count;
int foo[]; // not valid C++
};
struct blah
{
int count;
int foo[0]; // also not valid C++
};
據我所知,C ++ 0x也不會添加它。
但是,如果將數組的大小設置為1個元素:
struct blah
{
int count;
int foo[1];
};
事情是有效的,并且運作良好。您可以使用不太可能出現一次性錯誤的表達式分配適當的內存:
struct blah* p = (struct blah*) malloc( offsetof(struct blah, foo[desired_number_of_elements]);
if (p) {
p->count = desired_number_of_elements;
// initialize your p->foo[] array however appropriate - it has `count`
// elements (indexable from 0 to count-1)
}
因此,它可以在C90,C99和C ++之間移植,并且與C99的靈活數組成員一樣好用。
雷蒙德·陳(Raymond Chen)對此寫得很好:為什么有些結構以大小為1的數組結尾?
注意:在Raymond Chen的文章中,在初始化“靈活”數組的示例中有一個錯字/錯誤。它應顯示為:
for (DWORD Index = 0; Index < NumberOfGroups; Index++) { // note: used '<' , not '='
TokenGroups->Groups[Index] = ...;
}

TA貢獻1803條經驗 獲得超6個贊
第二個將不包含元素,而是指向blah。因此,如果您具有這樣的結構:
struct something
{
int a, b;
int c[0];
};
您可以執行以下操作:
struct something *val = (struct something *)malloc(sizeof(struct something) + 5 * sizeof(int));
val->a = 1;
val->b = 2;
val->c[0] = 3;
在這種情況下,c它將表現為5 ints 的數組,但數組中的數據將在something結構之后。
我正在研究的產品將其用作大小字符串:
struct String
{
unsigned int allocated;
unsigned int size;
char data[0];
};
由于受支持的體系結構,這將消耗8個字節plus allocated。
當然,所有這些都是C,但是例如g ++毫不費力地接受了它。
- 3 回答
- 0 關注
- 534 瀏覽
添加回答
舉報