c-如何使指针结构成员的行为像数组



我的结构中有一个指针。

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*(。

现在我实际上无法改变主体结构。我能做的是为Structure初始化提供不同的输入。有办法做到这一点吗?

您可以使用复合文字:

Structure some_struct = {10, (AnotherStructure []) { {20}, {30} }};

以及:

AnotherStructure x[] = { {20}, {30} };
Structure some_struct = {10, x};

语法(type) {list of initial values}创建一个对象。在上面的情况下,它创建一个AnotherStructure的数组,该数组自动转换为指针,该指针适用于初始化member2成员。(由于数组的每个元素都是一个结构,因此结构内部成员的初始值都包含在大括号中。(

当在任何函数之外使用时,对象将是静态的;其生存期将持续程序执行的持续时间。在函数内部,它将具有自动存储持续时间。其生存期将在其关联块的执行结束时结束。

您可以这样做:

long x = 20, y = 30;
long array[] = {x, y};
Structure some_struct = {10, array};

您只需要确保array的生存期结束后(即array超出范围后(不会取消引用some_struct.member2