[英]Initializing an array of pointers to structs containing a double pointer in c
[英]LCC: Initializing Structs Containing Structs?
以下代碼片段在Mac OS X上使用gcc編譯得很好,但無法在Windows上使用lcc-win32進行編譯:
typedef struct Foo Foo;
typedef struct Bar Bar;
struct Bar { int age; int height; };
struct Foo { Bar barOne; Bar barTwo; };
// Elsewhere, in some function:
Bar barOne = { 2, 4 };
Bar barTwo = { 6, 8 };
Foo instance = { barOne, barTwo };
並給出了這個錯誤:
發現'struct Bar'需要'int'
我可以通過這種方式初始化結構來“克服”這個:
Foo instance = { barOne.age, barOne.height, barTwo.age, barTwo.height };
所以,我理解發生了什么...但我覺得這會使我的代碼變得更復雜(我需要理解我正在使用的其他結構的實現和布局,而不是簡單地消耗它們 - 如果這樣的布局變化,我必須使用結構轉換給任何其他人。
我想知道LCC是“更嚴格”(堅持某種標准)還是“更愚蠢”(編譯器太愚蠢無法處理這種情況)。
謝謝。
另外,請參閱我的其他LCC-Win32問題: LCC:Typedef'd Enum的前向聲明失敗?
正如所寫:
typedef struct Foo Foo;
typedef struct Bar Bar;
struct Foo { Bar barOne; Bar barTwo; };
struct Bar { int age, int height };
// Elsewhere, in some function:
Bar barOne = { 2, 4 };
Bar barTwo = { 6, 8 };
Foo instance = { barOne, barTwo };
代碼應該無法在任何地方編譯(特別是在帶有GCC 4.6.0的MacOS X 10.7.1上失敗)以及這些錯誤(以及其他一些錯誤):
xx.c:4: error: field ‘barOne’ has incomplete type
xx.c:4: error: field ‘barTwo’ has incomplete type
這是因為您在定義之前嘗試使用Bar
。 顛倒結構定義的順序,並修復Bar中的語法錯誤(逗號應該是分號;缺少分號),然后(最后)它在MacOS X上編譯。
標准對使用結構作為初始化器有何看法?
§6.7.8初始化
¶13具有自動存儲持續時間的結構或聯合對象的初始化程序應該是如下所述的初始化程序列表,或者是具有兼容結構或聯合類型的單個表達式。 在后一種情況下,對象的初始值(包括未命名的成員)是表達式的初始值。
考慮一個函數的上下文(這段代碼可以用GCC設置繁瑣編譯):
typedef struct Foo Foo;
typedef struct Bar Bar;
struct Bar { int age; int height; };
struct Foo { Bar barOne; Bar barTwo; };
void somefunction(void)
{
Bar barOne = { 2, 4 };
Bar barTwo = { 6, 8 };
Foo instance = { barOne, barTwo };
}
從表面上看,它看起來像barOne
和barTwo
兩個不是單個表達式。 但是,標准繼續說:
¶16否則,具有聚合或聯合類型的對象的初始值設定項應該是元素或命名成員的大括號括起來的初始值設定項列表。
如果聚合必須是括號,那么寫這個將起作用:
Foo instance = { { barOne }, { barTwo } };
但是,海灣合作委員會強烈反對這種結構。
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)
/usr/bin/gcc -g -std=c99 -Wall -Wextra -Wmissing-prototypes -c xx.c
xx.c:8: warning: no previous prototype for ‘somefunction’
xx.c: In function ‘somefunction’:
xx.c:11: error: incompatible types in initialization
xx.c:11: warning: missing initializer
xx.c:11: warning: (near initialization for ‘instance.barOne.age’)
xx.c:11: error: incompatible types in initialization
xx.c:11: warning: missing initializer
xx.c:11: warning: (near initialization for ‘instance.barTwo.age’)
xx.c:11: warning: missing initializer
xx.c:11: warning: (near initialization for ‘instance.barOne’)
xx.c:11: warning: unused variable ‘instance’
總的來說,我傾向於相信海灣合作委員會的判斷,並指責LCC沒有有效處理案件。 爭論需要完整解析C標准的§6.7.8,並且我沒有提供所有的材料(在開始示例之前它會進入¶23)。
好吧,它有時候什么都不稱為Little C Compiler。 它可以處理大多數事情,但為了節省空間和時間,在這些情況下通常會更嚴格。 實現看起來很簡單的東西通常不在編譯器中。 無論是LCC還是LCC都沒有更新來處理這些情況。 是否有使用LCC而不是Borland,MSVC ++,Cygin / MingW32 gcc的特定原因?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.