【发布时间】:2016-07-30 09:43:33
【问题描述】:
我正在尝试创建一棵树,其中每个节点(结构)都有一个字符串字段作为其名称,队列* 字段用于包含其子节点的队列。
下面的示例代码是一个小程序,用于隔离我在大型复杂程序中收到的错误。它消除了与我的错误无关的任何内容,但类似于有问题的原始代码。我在与完整代码相同的位置收到相同的错误,这是运行时崩溃。编译时编译器不会给我任何警告。
当我尝试将节点推送到其中一个队列时发生崩溃,该队列在被指针引用后通过引用传递给函数。
我的代码中包含数字的 cmets 显示了它遵循的执行顺序。
#include <string>
#include <queue>
#include <iostream>
using namespace std;
using std::string;
using std::queue;
// the tree node structure
typedef struct Node
{
string name; // the name of this node
queue<Node>* children; // a queue containing the child nodes
} Node;
Node makeNode(string name)
{
queue<Node> children = {}; // 2, 7, 12
Node n = {name, &children}; // 3, 8, 13
return n; // 4, 9, 14
}
void funcTwo(queue<Node>& nodes)
{
Node n = makeNode("Child of Child of Root"); // 11
cout << "Program prints this." << endl; // 15
nodes.push(n); // PROGRAM CRASHES HERE
cout << "Program does not print this." << endl;
}
void funcOne(queue<Node>& nodes)
{
Node n = makeNode("Child of Root"); // 6
funcTwo(*n.children); // 10
nodes.push(n);
}
int main()
{
Node root = makeNode("Root"); // 1
funcOne(*root.children); // 5
return 0;
}
谢谢!
编译器:Microsoft (R) C/C++ 优化编译器版本 19.00.23506 for x86
操作系统:Windows 7 专业版
【问题讨论】:
标签: c++ pointers struct queue pass-by-reference