plate45 plate45 - 23 days ago 5
C++ Question

Trouble using an array in a class (C++)

I've looked through various forum posts from here and other sites however I have not seen anything referring to a similar problem. The problem I'm having is: the studentInfo array will not run properly besides when the array elements are 6 or below. I just want to be able to have an array with a size of 23, however the code returns:

bash: line 12: 51068 Segmentation fault $file.o $args


The code I've provided below is a simplified version of my actual code. I have to use an array in my program (no vectors as some may want to suggest) because it is part of my assignment. I am still a little new to c++ so a good explanation for any answers would be awesome. Thanks for any help!

#include <iostream>
#include <string>

using namespace std;

class StudentGrades {
private:
string studentInfo[23];

public:
void setStudentInfo(string info) {
for (int i = 0; i < 23; ++i) {
studentInfo[i] = info;
}
}

string getStudentInfo() {
for (int i = 0; i < 23; ++i) {
cout << studentInfo[i] << " ";
}
}
};

int main() {

StudentGrades student1;

student1.setStudentInfo("Bob");

student1.getStudentInfo();
}

Answer

The code has undefined behavior because member function getStudentInfo returns nothing though it is declared with non-void return type.

Declare it like

void  getStudentInfo() const {
    for (int i = 0; i < 23; ++i) {
        cout << studentInfo[i] << " ";
    }
}

Also it would be better not to use magic numbers. You can add a static constant data member in the class like this

class StudentGrades {
    private:
    static const size_t N = 23;
    string studentInfo[N];
    ....

and use it everywhere where it is needed. For example

void  getStudentInfo() const {
    for (size_t i = 0; i < N; ++i) {
        cout << studentInfo[i] << " ";
    }
}
Comments