繁体   English   中英

将值分配给结构中的数组

[英]Assign values to arrays in structs

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

例:

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,它应为数组中的下一个位置。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM