【问题标题】:Pointer stored in array changes value C++存储在数组中的指针更改值 C++
【发布时间】:2021-04-09 02:14:02
【问题描述】:

首先,我是 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++
  • 即使该声明有效,C++ 也没有动态数组。如果你想要一个动态数组,你需要std::vector
  • 更清楚一点...您没有为State* 分配任何空间。使用:State **list; ... list = new State*[max_num_objects];
  • 再次,使用std::vector
  • @AhmedMustafa 要创建动态数组,请使用指针和new[],要创建动态指针数组,请使用指向指针的指针,例如State** list; list = new State*[size];

标签: c++ arrays class pointers


【解决方案1】:

好的,您收到了一些 cmets。我将把它们放在一起形成一个完整的答案。这是你的主要问题:

    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 更好。

还请注意,处理指针本身是危险的,此外您还应该查看智能指针。

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多