This code is for a CS 235 class, but I'm new to C++ and I have no clue how they want me to do this. The grow function works by taking in an array and changing it to become twice as large. Coming from python, I guess this is the equivalent of mutating the array? Anyway, I can't get it do the same for the insert function. I need it to check if the position that we're trying to insert an item at is outside the array bounds and make the array big enough that it can insert the value. Everything works....inside the function. The array does not maintain the changes outside the function. I've tried passing it in as a pointer, as a (reference to a pointer?) like *&array, and basically any combination I can think of.
void grow(int *&original_array, unsigned int & capacity){
int *temp = new int[capacity * 2];
for (int i=0; i<capacity*2; i++){
temp[i] = 0;
}
std::cout << "line 18: ";
print_array(temp, capacity*2);
for(int i=0; i<capacity; i++){
temp[i] = original_array[i];
}
std::cout << "line 23: ";
print_array(temp, capacity*2);
// delete[] original_array;
original_array = temp;
std::cout << "line 27: ";
print_array(original_array, capacity * 2);
capacity = capacity * 2;
}
bool insert (int array[], unsigned int & maxSize, unsigned int & nFilled, unsigned int pos, int value){
while (maxSize < pos){
grow(array, maxSize);
print_array(array, maxSize);
}
for(unsigned int i = nFilled - 1; i >= pos; i = i-1){
array[i+1] = array[i];
}
array[pos] = value;
print_array(array, maxSize);
return true;
}
Here's some sample input and what my program outputs right now:
int main() {
unsigned int my_size = 4;
int new_array[4] = {1,2,3,4};
unsigned int nFilled = 4;
insert(new_array, my_size, nFilled, 5, 15);
print_array(new_array, my_size);
return 0;
}
Output:
line 18: {0, 0, 0, 0, 0, 0, 0, 0}
line 23: {1, 2, 3, 4, 0, 0, 0, 0}
line 27: {1, 2, 3, 4, 0, 0, 0, 0}
{1, 2, 3, 4, 0, 0, 0, 0}
{1, 2, 3, 4, 0, 15, 0, 0}
{1, 2, 3, 4, -152629248, 32758, 0, 8}
the second to last line is inside the function and the last one is outside the function. I need these to be the same
Any help is appreciated - the TA's and professors are being unhelpful
Thanks