0

我刚开始使用 C++,但我一直在解决一个非常烦人的问题。一旦我使用动态数组,我就被卡住了。数组在调试中看起来真的很乱(看图片),一旦我将更多的一个对象添加到数组中,它就会崩溃。这不是我得到一个特定项目的错误,而是所有使用动态数组的代码,我什至尝试编译老师在本课程中编写的代码,但没有成功。因此,问题不太可能是代码,但可能是其他问题。但是,为了安全起见,我确实包含了我用来证明这一点的测试代码。 代码调试

#include "iostream"
#include "string"
#include "Student.h"
int main()
{
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    string input;
    Student **students = NULL;
    students = new Student*[20];
    for(int i = 0; i < 20; i++)
    {
        students[i] = new Student();
    }
    for(int i = 0; i < 20; i++)
    {
        delete students[i];
    }
    delete[] students;
    return 0;
}



#include "Student.h"
#include "string"

Student::Student()
{
    name = "";
    number = 0;
}
Student::Student(string Name)
{
    name = Name;
    number = 0;
}
Student::~Student()
{

}
string Student::getName() const
{
    return name;
}



#ifndef STUDENT_H
#define STUDENT_H
#include "string"
#include "Course.h"
using namespace std;
class Student
{
private:
    string name;
    int number;
public:
    Student();
    Student(string Name);
    virtual ~Student();
    string getName() const;
};
#endif
4

1 回答 1

1

它在调试器中看起来混乱的原因是因为您试图查看student(您尚未分配,因此内容适当地无效)而不是数组students。调试器无法显示动态分配的数组。

还有,students = new Student();?这甚至不应该编译,而且逻辑是错误的。您正在将 a 分配Student*给 a Student**

作为一般规则,永远不要new[]在您自己的代码中使用。始终使用std::vector. 然后您将自动构建正确数量的Student类,并且永远不会泄漏内存或任何类似的事情。

int main() {
    std::vector<Student> students;
    string input;
    students.resize(20);
    // Now you can use ALL THE STUDENTS
    return 0;
}
于 2012-05-10T16:21:25.430 回答