简体   繁体   English

C ++简单指针错误无法弄清楚为什么?

[英]C++ Simple Pointer mistake can't figure out why?

I am trying to design a StudentReviewSystem, which simply has courses, students, etc. Now, I am trying to add a course object to the courses array. 我正在尝试设计一个StudentReviewSystem,它只包含课程,学生等。现在,我正在尝试将课程对象添加到课程数组中。 Since, I am doing it dynamically; 因为,我正在动态地做; when I insert a new course, I copy the olders to new array and insert new one. 当我插入一个新课程时,我将olders复制到新数组并插入新数组。 However, when I delete the older array it gives me invalid pointer error. 但是,当我删除旧的数组时,它会给我无效的指针错误。 I cannot figure out why? 我想不通为什么? Thanks for help. 感谢帮助。

void StudentReviewSystem::addCourse(int courseId, string courseName) {
    //increment number of courses
    setNumCourses(numCourses + 1);
    Course* newCourses = new Course[numCourses];

    if (courses != NULL) {
        // copy courses to new one
        for (int i = 0; i < numCourses - 1; i++) {
            newCourses[i].setCourseId(courses[i].getCourseId());
            newCourses[i].setCourseName(courses[i].getCourseName());
        }

        // delete old courses
        delete courses;
    }

    newCourses[numCourses - 1].setCourseId(courseId);
    newCourses[numCourses - 1].setCourseName(courseName);
    courses = newCourses;
}

This is courses class. 这是课程课程。

#include "Course.h"
Course::Course() {
}

Course::~Course() {
}

int Course::getCourseId() const {
    return courseId;
}

void Course::setCourseId(int courseId2) {
    courseId = courseId2;
}

string Course::getCourseName() const {
    return courseName;
}

void Course::setCourseName(string courseName2) {
    courseName = string(courseName2);
}

And this is the main. 这是主要的。

int main() {
    StudentReviewSystem srs;

    srs.addCourse(111, "foo");

    srs.addCourse(222, "foo");

    srs.addCourse(333, "foo");

    srs.addCourse(444, "foo");

    return 0;
}

I think you forgot something: delete [] courses; 我想你忘了点: delete [] courses; actually deletes the array - you were only deleting the pointer. 实际上删除了数组 - 你只是删除了指针。

This isn't an answer to your problem, but I'd like to show you could do this with the standard library. 这不是您的问题的答案,但我想告诉您可以使用标准库执行此操作。 One way is std::map, one is std::vector. 一种方法是std :: map,一种是std :: vector。

I suggest a map: 我建议一张地图:

#include <map>
#include <string>
std::map<int, string> courses;

To add a course: 要添加课程:

courses[111] = "foo";

Number of courses: 课程数量:

courses.size();

Or you could use std::vector instead. 或者你可以使用std :: vector代替。

#include <vector>
std::vector<Course> courses;

To add: 加上:

courses.push_back(Course(111, "foo"));

Number of courses look the same as with map. 课程数量与地图相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM