单次运行时指针值的变化
Change of pointer value at single run
我正在尝试构建一个 Oct 树结构,但在运行过程中指针的值似乎发生了变化。 insert(( 通过将子节点随机添加到父节点来模拟插入,show(( 用于显示路径上的所有元素。
每次 insert(( 和 show(( 打印节点及其子节点时,但结果不一致。
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 <<"nnn";
}
}
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;
}
在show()
中,您正在更新temp
,同时仍然循环遍历其子级:
...
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];
}
}
您可以使用辅助变量来存储指向要在下一级别使用的节点的指针,然后在循环之外更新temp
,例如:
Box* next = nullptr;
...
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))
{
next = temp->children[j];
}
}
temp = next;
它是在单次运行期间还是在运行之间发生变化?
由于使用的是动态内存,因此存储数据的地址(指针值(可能会因运行而异。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- C++取消引用指针.为什么会发生变化
- 为什么向量内部的指针在从函数返回时会发生变化?
- 单次运行时指针值的变化
- 从旧的 C 样式指针移动到C++智能指针,代码几乎没有变化
- 共享指针和回调注册的结构.由于我之外的原因调用回调时,原始指针值发生了变化
- 指针参数根据输出而变化
- C++指针值发生变化
- 指针如何变化
- 链表头指针在传递给函数c++时发生变化
- 将指针从一个向量复制到另一个向量;地址指出了变化
- 如果我将堆栈上分配的元素的指针推入 std::vector,则其成员的值会发生变化
- 迭代器的指针在循环中如何变化C++
- 为什么指针会发生变化
- 在C++中遍历树时指针发生变化
- 指针随时间的改进/变化