gpt4 book ai didi

c++ - 定义递归结构的嵌套数组

转载 作者:太空宇宙 更新时间:2023-11-04 14:16:34 24 4
gpt4 key购买 nike

我有一个名为 Recursive 的简单递归结构,我想用程序需要的值初始化它的常量数组。然后,我将使用一个名为 IterateAux 的简单迭代器函数,并在 main 中调用它。看看到目前为止的代码:

#include <iostream>
#include <string>

struct Recursive
{
std::string data;
Recursive* Children;
};

void IterateAux(Recursive* Item)
{
int i = -1;
while (Item[++i].data != "")
{
std::cout << Item[i].data << "\n";
if (Item[i].Children)
IterateAux(Item[i].Children);
}
}

int main()
{
IterateAux( (Recursive*)Parent );
return 0;
}

现在,如果我有这样的 const 数组,它就可以工作了:

const Recursive Children[] =  {
{"Child1", NULL},
{"Child2", NULL},
{"", NULL}
};

const Recursive Parent[] = {
{"Parent1", NULL},
{"Parent2", NULL},
{"Parent3", Children },
{"", NULL}
};

但是下面的嵌套形式不会:

const Recursive Parent[] = {
{"Parent1", NULL},
{"Parent2", NULL},

{"Parent3", (Recursive[])
{
{"Child1",NULL},
{"Child2",NULL},
{"", NULL}
}
},
{"", NULL}
};

问题是为什么?我怎样才能让它发挥作用?

在我的调查中,起初我认为 .children 指针可能无效,但是当尝试使用 int 数据而不是 std::string 它完美地工作。

使用 std::string 数据时,GDB 崩溃并显示消息 During startup program exited with code 0xc0000135. 所以我什至无法调试程序!也许数组初始化代码在某处弄得一团糟......

在 GCC 4.6 上尝试了所有这些。

最佳答案

通过一些工作,我可以让它出现在 gdb 中。在 IterateAux 的 while 语句处设置断点。它通过 Parent 很好,然后当 t 到达 Children 案例时,我在工作案例中看到了这一点:

(gdb) p Item[0]
$2 = {data = "Child1", Children = 0x0}

在失败的情况下:

(gdb) p Item[0]
$2 = {data = <error reading variable: Cannot access memory at address 0xfffffff4>,
Children = 0x48d24d79}

所以看起来 Recursive[] 的转换隐藏了一个事实,即它没有编译成与第一种情况相同的形式。

我正在使用带有 -Wall 的 g++ 4.6.3 进行编译,没有收到任何警告。

关于c++ - 定义递归结构的嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10665439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com