单次运行时指针值的变化

Change of pointer value at single run

本文关键字:变化 指针 运行时 单次      更新时间:2023-10-16

我正在尝试构建一个 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;

它是在单次运行期间还是在运行之间发生变化?

由于使用的是动态内存,因此存储数据的地址(指针值(可能会因运行而异。