C++ 单次运行时指针值的更改
我试图构建一个Oct树结构,但指针的值在运行期间似乎发生了变化。insert()通过向父节点随机添加子节点来模拟插入,show()用于显示路径上的所有元素 每次insert()和show()打印节点及其子节点时,结果都不一致C++ 单次运行时指针值的更改,c++,pointers,C++,Pointers,我试图构建一个Oct树结构,但指针的值在运行期间似乎发生了变化。insert()通过向父节点随机添加子节点来模拟插入,show()用于显示路径上的所有元素 每次insert()和show()打印节点及其子节点时,结果都不一致 geometry.h #pragma once #include<random> class Box { public: Box * parent; Box ** children; public: Box() {
geometry.h
#pragma once
#include<random>
class Box
{
public:
Box * parent;
Box ** children;
public:
Box()
{
parent = nullptr;
children = new Box*[8];
for (int i = 0; i < 8; i++)
{
children[i] = nullptr;
}
}
Box(const Box &rhs)
{
parent = rhs.parent;
children = new Box*[8];
for (int i = 0; i < 8; i++)
{
children[i] = nullptr;
}
}
Box & operator =(const Box &rhs)
{
if (this == &rhs)
{
return *this;
}
else
{
parent = nullptr;
for (int i = 0; i < 8; i++)
{
children[i] = nullptr;
}
}
}
};
class Tree
{
public:
Box rootnode;
int depth;
Tree(int _depth) { depth = _depth; }
void insert()
{
Box * temp;
temp = &rootnode;
for (int i = 0; i < depth; i++)
{
std::cout << temp << std::endl;
//random choose a child
int p=rand()%8;
std::cout << p << std::endl;
//creat a new child node and save the
//address to children
temp->children[p] = new Box();
for (int k = 0; k < 8; k++)
{
std::cout << temp->children[k] << " ";
}
std::cout << std::endl;
// go to the next layer
temp = temp->children[p];
std::cout << temp <<"\n\n\n";
}
}
void show()
{
Box * temp;
temp = &rootnode;
for (int i = 0; i < depth; i++)
{
std::cout << temp << std::endl;
for (int j = 0; j < 8; j++)
{
std::cout << temp->children[j] << " ";
// if it have a child go to that child node
if (!(temp->children[j] == nullptr))
{
temp = temp->children[j];
}
}
std::cout << std::endl;
}
}
};
#include<iostream>
#include<vector>
#include"geometry.h"
int main()
{
Tree thistree(9);
thistree.insert();
thistree.show();
system("PAUSE");
return 0;
}
geometry.h
#布拉格语一次
#包括
类框
{
公众:
框*父项;
方框**儿童;
公众:
框()
{
父项=nullptr;
儿童=新框*[8];
对于(int i=0;i<8;i++)
{
儿童[i]=nullptr;
}
}
接线盒(常数接线盒和右侧接线盒)
{
parent=rhs.parent;
儿童=新框*[8];
对于(int i=0;i<8;i++)
{
儿童[i]=nullptr;
}
}
框和运算符=(常数框和rhs)
{
如果(此==&rhs)
{
归还*这个;
}
其他的
{
父项=nullptr;
对于(int i=0;i<8;i++)
{
儿童[i]=nullptr;
}
}
}
};
类树
{
公众:
盒根节点;
智力深度;
树(int_depth){depth=_depth;}
空白插入()
{
盒子*温度;
temp=&rootnode;
for(int i=0;i std::cout在单次运行期间,还是在两次运行之间发生变化
由于您使用的是动态内存,存储数据的地址(指针值)可能会在不同的运行中发生变化。在show()
中,您正在更新temp
,同时仍在循环其子级:
。。。
对于(int j=0;j<8;j++)
{
std::cout children[j]children[j]==nullptr)
{
>>>>temp=temp->children[j];
}
}
您可以使用一个辅助变量来存储指向下一级要使用的节点的指针,然后在循环外部更新temp
,例如:
Box*next=nullptr;
...
对于(int j=0;j<8;j++)
{
std::cout children[j]children[j]==nullptr)
{
下一步=临时->子项[j];
}
}
温度=下一个;
我知道这不是实现Oct树的好方法,我只是想知道为什么这不起作用,也许是因为“nullptr”初始化?谢谢你的关注,我想它在单身期间改变了run@florgeng