【发布时间】: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<struct*>代替吗? -
(&childHaver, &noChild)使用逗号运算符,而不是传递多个东西。而且那个 struct hack 不是有效的 C++。 -
向量可能会起作用,但这取决于我的开发主管。他不喜欢他们。传递多个东西的语法是什么?
-
你没有任何结构数组。
标签: c++ pointers recursion struct