C++ - incrementing integer variable does not work

So I'm creating a program that implements several classes representing a school, and its students and courses. I'm running into an issue in School.cc where the addTaken() finds the student object with the given student number and the course object with the given course code, and then creates a new Taken object with the found student and course objects and adds it to the back of the Taken collection which is studentCoursePairs[].

The problem is the variable numTaken never increments despite having the '++'. It seems to always stay at 0. If numTaken is 0, the loop immediately stops (as 0 < 0 is false) and numTaken is never incremented for this reason. I was wondering if anyone knows how to fix this?

Since numTaken is always 0 it won't let me print anything in the Taken collection out.

School.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <iomanip>
using namespace std;
#include <string.h> 

#include "School.h"

School::School(string s1) : name(s1){ 
    numTaken = 0;
}

void School::addTaken(string number, int code, string grade){
    Student* s = nullptr;
    Course* c = nullptr;
    if((studentsCollection->find(number, &s)) && (coursesCollection->find(code, &c))){
        Taken* taken = new Taken(s, c, grade);
        studentCoursePairs[numTaken] = taken;            
        ++numTaken;
    }
}
void School::printTaken(){
    cout << name << " === TAKEN: "<< endl;
    for(int i = 0; i < sizeof(studentCoursePairs)/sizeof(studentCoursePairs[0]); ++i){
        studentCoursePairs[i]->print(); //seg fault
    }   
}


StudentCollection.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
#include <string.h> 
#include "StudentCollection.h"

StudentCollection::StudentCollection(){
    students = new Student*[MAX_STUDENTS];
    size = 0;
}


bool StudentCollection::find(string num, Student** s){
    for(int i = 0; i < size; ++i){
        if(students[i]->getNumber() == num){ //find student number
            *s = students[i];
            return true;
        }
        return false;
    }
}


CoursesCollection.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
#include <string.h> 
#include "CoursesCollection.h"

CoursesCollection::CoursesCollection(){
  Course* courses = new Course(); 
  numCourses = 0;
}

bool CoursesCollection::find(int id, Course** c){
    for(int i = 0; i < numCourses; ++i){
        if(courses[i]->getId() == id){ //find course id
            *c = courses[i];
            return true;
        }
        return false;
    }
}
Last edited on
Topic archived. No new replies allowed.