I don't know why the insert function isn't running

Asked 2 years ago, Updated 2 years ago, 32 views

Error content: It runs on line 137, but I think there is a problem with the insert function. I turned on the debugs Exception thrown: read access violation. _My_data was nullptr. What's wrong with that?

class student {
public:
    string name;
    int id;
    string grade;};

class table {
public:
    int tsize, size;
    int idx = 0;
    table(int n);
    student *stp;
    void insert(string name,int id,string grade);
};

table::table(int size) {
    tsize = size;
} // Class constructor receiving int size

void table::insert(string name,intid,string grade) { // Problematic
    if (idx < tsize) {
        stp[idx].name = name;
        stp[idx].id = id;
        stp[idx].grade = grade;
        idx++;
    }
    else
        cout << "table full";
}

int main() {

    int size;
    string name;
    int id;
    string grade;

    cout << "Enter the number of students >>" << endl;
    cin >> size;
    table t(size);
    for (int i = 0; i < size; i++) {
        cout << "Enter student information (in order of name, grade)" << endl;
        cin >>name;
        cin >>id;
        cin >>grade;
        t.insert(name,id,grade); //insert function issue
        }

}

c++

2022-09-22 18:33

1 Answers

The error occurs because the insert() pointer is not initialized and the insert() call process accesses the wrong memory.

Please revise it as below.

table::table(int size) {
    tsize = size;
    stp = new student[size];
} // Class constructor receiving int size

And I think we need to add an extinction.

table::~table() {
    delete[] stp;
}


2022-09-22 18:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.