When you add your first student, students
is set to point to s
inside the AddStudent
function. The problem is since s
is local to the function, it is destroyed when the function returns. So students
is now a dangling pointer pointing to nowhere since the memory it points to is no longer used to store the Student
object. In order to keep the memory after the AddStudent
function returns, you would have to dynamically allocate it with new
, but there are other problems with that.
Let's say you dynamically allocate the memory for the new student. When we add a second student, some more memory will be allocated to store that. That new memory could end up being in a totally different place. Your AddStudent
function will set the students
pointer to point to the new Student
object, but now we've forgotten where the existing student is stored.
So how do we fix this? We could allocate an array of Student
objects, leaving extra space for new students. This way, all the students are stored in a contiguous piece of memory, and students
will always point to the first object. In our AddStudent
function, we would put the new student after the last student we currently have by doing something like students[nstudents] = s
, before incrementing nstudents
.
The problem with this is that if we exceed the capacity of the array, we would have to allocate a new larger array and copy everything over since we can't expand an existing block of allocated memory. Or you could just make the array fixed sized. But there's a better solution: std::vector
.
std::vector
is a standard library container that manages the memory for you. You can store your students there and easily add one using push_back
. You can learn how to use vectors by asking your instructor, reading a good book, or finding a tutorial online (do note that there are many bad ones out there).