2012-05-10 77 views
0

我刚刚开始使用C++,但我一直在破坏一个非常恼人的问题。只要我使用动态数组,我就卡住了。该数组看起来真的搞乱了调试(看图片),只要我添加更多的一个对象到它崩溃的数组。这不是一个错误,我得到一个特定的项目,但所有使用动态数组的代码,我甚至尝试编译在这门课程中由老师编写的代码,但没有成功。所以它不可能是代码是问题,但可能是别的。然而,我确实包含了我用来证明这只是安全的测试代码。 Debug of the code阵列与第一个索引崩溃

#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 
+2

我没有看到您将学生添加到数组中。请更新你的问题,你怎么把学生对象放入数组 – Attila

+4

你应该考虑使用'std :: vector'或其他一些STL容器。 – mfontanini

+2

您的测试演示无法检查NULL指针指向的值。有什么令人惊讶的呢? –

回答

1

它会在调试器搞砸的原因是因为你正试图查看学生(你还没有分配,因此内容是适当的无效)不是数组学生 。调试器不能显示动态分配的数组。

另外,students = new Student();?这甚至不应该编译,并且逻辑是错误的。您将Student*分配给Student**

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

int main() { 
    std::vector<Student> students; 
    string input; 
    students.resize(20); 
    // Now you can use ALL THE STUDENTS 
    return 0; 
} 
+0

我同意,但由于某种原因,我认为这是一个教室的设置。我在他的文章中评论了他的指针矩阵。 – johnathon

+0

@johnathon:作为一间教室,使用'std :: vector'的*更重要,而不是更少。 – Puppy

+0

是啊,恩,相信我我已经见过课室设置C++,cs101学生作业,并相信我,std和STL不在其中。 – johnathon