Segmentation Error in Void Function

Hey guys, I'm new here and to c++ in general and have run into some trouble of a project I'm working on. One function within this project is giving me trouble. The goal is just to search a structured array for a particular student ID and if its contained in the array, then display the name of that student, and if its not there, display an error message. I wrote out the code for this and it compiles fine but I get a segmentation error everytime I go to test it, and can't see why. When I read through it, it looks like it should work, so I am hoping someone here can spot my error. Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  void studentInquiry(const Student roster[], int numStuds, string sID)
{
        int i = 0;

        while(sID != roster[i].studentID || i <= numStuds)
                i++;

        if(sID == roster[i].studentID)
        {
                cout<<roster[i].studentID<<"\t"<<roster[i].firstName<<"\t";
                cout<<roster[i].midInitial<<"\t"<<roster[i].lastName<<endl;
        }
        else
                cout<<"A student with this ID number is not assigned to this roster. "<<endl;

}
What do you think is stored at roster[i], when i is equal to numStuds?

What do you think is stored at roster[i], when i is equal to numStuds + 1?
Last edited on
When i is equal to numStuds, you are viewing the last student on the roster. And anything after that is nothing and would get an error if I tried to go there. So I assume that's what causing my issue. But the way I see it, the while loop should end before i gets incremented beyond numStuds. But I must be wrong about that.
My logical operator must be wrong and allowing the while loop to continue.
When i is equal to numStuds, you are viewing the last student on the roster.

Are you sure? Remember that in C++, array indices start at 0, not 1.

But the way I see it, the while loop should end before i gets incremented beyond numStuds. But I must be wrong about that.

But look at what happens in your loop. When i is equal to numStuds, the loop still iterates, so i gets incremented to numStuds + 1.
Oh wow. I can't I forgot about that, so the while loop is causing a error even when i = numStuds because thats one more index than roster[numStuds] has. And on top of that it increments it again and goes even further.
Exactly :)

The starting-from-zero thing is something that can take a while to sink in, unfortunately!
Knowing that I should be able to get it sorted. Thanks so much!
You're welcome :)
Topic archived. No new replies allowed.