1

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. Since, I am doing it dynamically; when I insert a new course, I copy the olders to new array and insert new one. 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;
}
anjruu
  • 1,164
  • 8
  • 22
memn
  • 135
  • 6

2 Answers2

2

I think you forgot something: delete [] courses; actually deletes the array - you were only deleting the pointer.

Eutherpy
  • 4,211
  • 4
  • 30
  • 60
1

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.

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.

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

To add:

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

Number of courses look the same as with map.

dutt
  • 7,415
  • 11
  • 50
  • 81
  • Thanks for your suggestions but i need to do this in that way. – memn Nov 21 '13 at 13:12
  • It seems that OP doesn't need "always-sorted". if so, using `std::vector<>` is much better for performance. – ikh Feb 25 '14 at 01:14