【发布时间】:2020-03-18 19:17:10
【问题描述】:
我有以下嵌套的struct 定义:
typedef struct {
int count;
float cash;
char item[50];//switch between array and pointer for testing initializers
//char *item;
}Purchase;
typedef struct {
int accnt;
char acct_name[50];
Purchase purch;
} Acct;
对于 Purchase struct 本身,以下初始化程序起作用:
//Uses member names:
/* 1 */Purchase p = {.count = 4, .cash = 12.56, .item = "thing"};
// Note: this member: ^^^^^^^^^^^^^^^
对于嵌套结构Acct,以下工作:
// No member names:
/* 2 */Acct acct = {100123, "Robert Baily", {15, 12.50, "Tires"}};
// ^^^^^^^
但是当我尝试使用成员名称时,如第一个示例所示:
// Attempts to use member name, but fails the last one:
/* 3 */Acct acct3 = {.accnt = 100123, .acct_name = "Robert Baily", {acct3.purch.count = 15, acct3.purch.cash = 12.50, acct3.purch.item = "Tires"}};
// error occurs here -> ^
我收到此错误:22, 131 error: array type 'char [50]' is not assignable
使用会员char item[50]; inPurchase时`
我得到这个错误:22, 14 error: initializer element is not a compile-time constant
在Purchase 中使用成员char *item; 时
(注意任何时候只有一个版本的item是struct的一部分,其他的被注释掉了)
因此,总而言之,如果不使用上述语句/* 2 */ 中的命名赋值语句,我可以初始化一个嵌套结构,但是当我尝试使用如语句char [] 中所示的命名赋值语句/* 3 */ 中的类型时,它失败了。
当 char [] 或 char * 是嵌套结构构造的内部结构的成员时,我缺少什么初始化?
我正在使用设置为 C99 的 CLANG
【问题讨论】:
-
为什么不是
... {.purch.count = 15, .purch.cash = 12.50, .purch.item = "Tires"}}? -
@DavidC.Rankin - 我确实尝试过。对于这些尝试,我收到错误消息:
23, 63 error: field designator 'purch' does not refer to any field in type 'Purchase'。 (即使其他两个成员使用相同的名称。purch.count和purch.cash没有问题) -
是的,让我再仔细看看。我记得这不是很早以前就咬我了,我记得结果是对于嵌套结构,您必须为所有成员提供初始化(尽管标准允许摆动空间),但我必须刷新并查找它。给我几分钟。
-
@DavidC.Rankin - 在我所有的尝试中,我正在初始化所有成员。
标签: c struct nested designated-initializer