【发布时间】:2021-05-23 09:27:43
【问题描述】:
我的结构中有一个指针。
typedef struct AnotherStructure
{
int member1;
} AnotherStructure;
typedef struct Structure
{
int member1;
AnotherStructure* member2;
} Structure;
AnotherStructure x = {0};
该指针的行为不应像普通指针,而应像数组一样。现在我有了另一段代码,
Structure some_struct = {10, {&x, NULL /* Sentinel */}};
这不起作用。我知道为什么。这是因为它试图初始化一个指针但没有这样做,因为第一个元素既不是指针也不是地址,而且我们为它提供了多个初始化器。不过我也试过了,
AnotherStructure* array[] = {&x, NULL};
Structure some_struct = {10, array};
这也不起作用,因为有不同的间接方式(AnotherStructure** 到 AnotherStructure*)。
现在我实际上无法更改主要结构。我能做的是为结构初始化提供不同的输入。有办法吗?
【问题讨论】:
-
改用
long array[] = {20, 30};。并希望数组的生命周期至少与结构的生命周期一样长。 -
错误 C2099:初始化程序不是常量
-
这就是它现在显示的内容
-
AnotherStructure* array[] = {&x, NULL};/Structure some_struct = {10, array};不起作用是因为类型错误,而不是因为初始化程序必须是常量。如果您希望membe2成为指向AnotherStructure的指针,则必须使用指向AnotherStructure的指针来初始化它,而不是使用指向AnotherStructure的指针。展示您要创建的实际结构的真实示例。 -
@EricPostpischil 很抱歉造成混淆,这是对某个程序员老兄的回复。我的实际错误是你描述的那个
标签: c visual-c++ c99