I'm stuck on how to increase the size of my structure array through a grow function without using a vector.(not allowed to use vectors in this)I have to read data from a file and if my set array size is too small i have to increase the array by passing it into a function. Here is the directions.
--For your “grow” function, pass the pointer to the array by reference. Also pass the current size by reference. Using a local pointer, point this to the array that was passed in. Next determine how much memory will be added to the array – old size versus new size. Select an appropriate grow factor. Using the pointer passed in, allocate the new memory, copy the data from the old array (pointed to by your local pointer), set the size to the new size, then deallocate the old memory.
Here is my code i have for this part of my program(does a lot more but just need this part to work)
void ReadStudentData(ifstream& infile, StudentType*& student, int& numStudents)
{
string first, last;
int Tscore;
int index = 0;
student = new StudentType[numStudents];
if (student == nullptr)
{
string error = "Error, bad memory allocation";
throw error;
}
while (infile >> first >> last >> Tscore)
{
if (Tscore >= 0 && Tscore <= 100)
{
student[index].StudentName = last + ", " + first;
student[index].testScore = Tscore;
index++;
if (index == numStudents)
{
Grow(student, numStudents);
}
}
}
numStudents = index;
}
This is my grow function---
void Grow(StudentType* student[], int &numStudents)
{
int Increased = 4;
StudentType *Lptr = nullptr;
I'm in CSM10A so not sure what going on with that fully. I mainly need to take in a pointer to an array of structures that was dynamically allocated and copy it and delete the old one. But this is sent into a function from inside a loop that is trying to fill it with info from a file. So if my array had 15 students and there were 20 students in the file it should trigger the grow function to increase the size of the array and continue filling the array with the rest of the students. But i am only allowed to increase the number of students by 4 at a time so it should increase in my loop at least twice. I am ok with pointers but not well.
What cire posted will do what you want, you just have to change the type.
You need to pass the student array pointer by reference: void Grow(StudentType* &student, int &numStudents)
Newptr = CopyArrayForSorting(*student, numStudents);
I suspect this is wrong because you've already incremented the newStudents. Also, the first argument should probably be student instead of *student.
I suggest that you create a local variable called newSize so you have easy access to the old size and the new size. At the very end, change numStudents students to their new values: