0

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();
}
1
  • 1
    How simplified is it? One problem is that getStudentInfo doesn't return a string. Commented Nov 12, 2016 at 23:33

1 Answer 1

1

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] << " ";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.