【问题标题】:Assign values to arrays in structs为结构中的数组赋值
【发布时间】:2014-06-05 16:51:41
【问题描述】:

我正在使用一个结构,它在其中有一个指向其他相同类型结构的指针数组。如何在设计时分配该数组以具有多个元素?

例子:

struct structx {
int value;
structx *pChild[];
};

void funcY(hasChild*, int);

struct structx noChild = { 1, NULL };

struct structx otherNoChild = { 2, NULL };

struct structx childHaver = {
3,
&noChild
};

struct structx parent = {
4,
&childHaver
};

int _tmain(int argc, _TCHAR* argv[])
{
funcY(&parent, 0);

cout << endl;

funcY(&childHaver, 0);

system("pause");
return 0;
}

void funcY(hasChild* child, int childPosition)
{
if (child->pChild[0] != NULL)
{
    funcY(child->pChild[childPosition], childPosition);
}
cout << child->value << endl;
}

此代码适用于 Visual Studio 2008 中的 C++。

当我使用这段代码时,它工作得很好,并打印出 1、3、4。

但是,如果我尝试将多个地址放入结构中,如下所示:

struct structx parent = {
4,
(&childHaver, &noChild)
};

尽管在位置 0 发送,它会选择 &noChild,它应该是数组中的下一个位置。

在我缺少的语法中是否有一种特殊的方法可以做到这一点?

【问题讨论】:

  • 是否需要使用指向structx 的指针数组?你能用std::vector&lt;struct*&gt;代替吗?
  • (&amp;childHaver, &amp;noChild) 使用逗号运算符,而不是传递多个东西。而且那个 struct hack 不是有效的 C++。
  • 向量可能会起作用,但这取决于我的开发主管。他不喜欢他们。传递多个东西的语法是什么?
  • 你没有任何结构数组。

标签: c++ pointers recursion struct


【解决方案1】:

使用花括号来初始化结构数组。

struct structx parent = {
4,
{&childHaver, &noChild}
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2021-05-19
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 2016-06-16
    相关资源
    最近更新 更多