当我尝试构建八叉树结构时堆栈溢出
Stack overflow when I try to build an octree structure
我想建立一个n维树。我使用vector
来存储每个节点的子节点。我写的代码给出了"堆栈溢出错误",我不知道为什么,我确实使用了new
.如果有人能告诉我哪里出错了,我将不胜感激。
class Node
{
public:
int q_number;
int layer;
int value;
vector<Node*> n_list;
Node(int n):q_number(n),n_list(n) //initialize node vector
{
}
};
Node* buildtree(int n,int depth)
{
Node * node = new Node(depth);
if(n==depth-1)
{
for(int i = 0; i<depth;i++)
{
node->n_list[i] = NULL;
node->n_list[i]->value = i;
node->n_list[i]->layer = depth-1;
}
}
else
{
for (int i =0;i<depth;i++)
{
node->n_list[i] = buildtree(n++,depth);// span the tree recursively
node->n_list[i]->value = i;
node->n_list[i]->layer = n; // the layer value
}
}
return node;
}
int main()
{
Node * tree = buildtree(0,8); // build an octree
}
正如 Dolda2000 所注意到的,在递归调用buildtree
时,您正在递增n
。因此,n
在其旧值(未更改(传递给函数后递增。因此,您有无限的buildtree(0,8);
调用堆栈,这自然会导致堆栈溢出。
预递增 - buildtree(++n,depth);
- 可以解决堆栈溢出的问题,但在这种情况下这不是您想要的,因为您在递归调用后使用n
。正如我理解您的意图,您不希望n
的值在递归调用后发生变化。
在您的情况下,解决方案只是:
buildtree(n+1,depth);
您的代码中还有另一个问题:
node->n_list[i] = NULL; // ok, the pointer is NULL now
node->n_list[i]->value = i; // trying to dereference a NULL pointer => error
node->n_list[i]->layer = depth-1;
您需要在此处使用new Node(...)
,或者将向量的值类型从 Node*
更改为 Node
,...或者确保在取消引用指针之前正确设置指针。
附言并确保n <= depth-1
- 通过断言,或在代码中包含注释,至少以避免以后进行大量调试。
相关文章:
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 如何在C++中为堆栈动态创建结构?
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 我的堆栈和库存清单程序的结构有什么问题?
- 当我尝试为结构分配新指针时出现堆栈溢出错误
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- C++ 堆栈推送方法不会将结构推送到堆栈上,只是返回 0
- 是否可以检查存储在堆栈上的单词是否是回文,而C++中没有任何附加数据结构
- 递归如何使用堆栈数据结构
- 构建模板 使用矢量 c++ 的堆栈结构
- 比较堆栈数据结构 c++
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- Boost::序列化存储结构时的堆栈溢出错误
- 堆栈(数据结构)实现
- 如何在C 中的标准堆栈中推动结构类型变量
- 您如何声明类型结构的堆栈?在C 中
- 使用boost::序列化递归图结构时,如何防止堆栈溢出
- 将记录推送到数据结构中的堆栈
- 无法创建数组大小 [300][300] 的二维数据结构 - >堆栈溢出
- 从结构堆栈弹出时释放内存