我刚刚开始使用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
我没有看到您将学生添加到数组中。请更新你的问题,你怎么把学生对象放入数组 – Attila
你应该考虑使用'std :: vector'或其他一些STL容器。 – mfontanini
您的测试演示无法检查NULL指针指向的值。有什么令人惊讶的呢? –