c++ - 存储在数组中的指针更改值 C++
问题描述
首先,我是 C++ 的菜鸟,所以我很有可能犯了一个愚蠢的错误。但是我无法弄清楚问题所在。
我有一个名为的对象类State
,我创建了一个自定义类List
,用于存储、添加和删除State
对象实例的指针引用。
这是该List
课程现在的样子:
class List
{
// VARIABLES
private:
State* list[];
public:
int length;
// CONSTRUCTOR
List()
{
length = 0;
}
// Add elements to list
void add(State* s)
{
list[length] = s;
cout<<length<<" "<<list[length]<<endl; // Print the recently added element
length++;
}
// Print all the elements in the array
void show()
{
cout<<endl;
for (int i = 0; i < length; i++)
{
cout<<list[i]<<endl;
}
}
}
这是我在main
函数中的代码:
int main()
{
// Initialize States
State s1 = State();
State s2 = State();
State s3 = State();
// Initialize List
List open = List();
// Print Original Addresses of States
cout<<&s1<<endl;
cout<<&s2<<endl;
cout<<&s3<<endl;
// Add Addresses to List
cout<<endl;
open.add(&s1);
open.add(&s2);
open.add(&s3);
// Loop over list to print addresses
open.show();
return 0;
}
这是输出:
0x70fad0
0x70fbe0
0x70fcf0
Element added at index 0 : 0x70fad0
Element added at index 1 : 0x70fbe0
Element added at index 2 : 0x70fcf0
0x30070fad0
0x70fbe0
0x70fcf0
State 对象的地址和添加到列表中的地址都是一样的,但是当循环列表显示地址时,第一个地址是0x30070fad0
而不是,0x70fad0
其余的都可以!
我不知道为什么会这样。
解决方案
好的,您收到了一些评论。我将把它们放在一起形成一个完整的答案。这是您的主要问题:
State* list[];
这是一个糟糕的代码,但听起来你的编译器让你这样做。这表明您有一组状态指针。伟大的。
阵列有多大?
答:未知。我们不知道您要占用多少空间。
C++ 没有像 Java(和其他语言)那样的动态数组。你不能只增长一个数组。正确的方法是:
#include <vector>
std::vector<State *> list;
这将要求您了解如何使用 std::vector。
老式(现在已过时)方法是使用指向指针的指针:
State ** list = nullptr;
int allocated = 0;
int length = 0;
然后,您的添加代码需要查看:
if (length >= allocated) {
// More space is required
allocated += 16; // or whatever size you want to grow by
State ** newList = new State *[allocated];
for (int index = 0; index < length; ++index) {
newList[index] = list[index];
}
delete[] list;
list = newList;
}
这很麻烦,容易出错,并且容易发生内存泄漏,这就是为什么使用 std::vector 更好。
另请注意,处理指针本身是危险的,此外您还应该查看智能指针。
推荐阅读
- android-studio - 使用新的导航架构组件滚动视图不会在片段中向上滚动
- python - 如何检查顶点匹配并替换边缘上的重复索引?
- dia - Block Dia Diagram Editor 保存文件的备份副本
- css - 使用 ` 为 SVG 生成 IMG src 数据 URI
- python-3.x - 如何根据时间戳从数据框中删除重复条目?
- python - pip install pywin32 在 mac 机器上失败
- windows - LLVM 在 Windows 上构建:跳过了 Visual Studio cl.exe
- c# - Emgu GetAverage 图像的黑色颜色
- javascript - TypeError:Discord.Streaming 不是函数
- r - ggsave 不保存仅最后一个情节