Create a dynamic array of int with a initial space of 4. Write a function ‘append’ that appends a given value to this array. At any stage, if this function finds the array full it automatically doubles the size of array to accommodate this new value. Also write a function to display all the elements of this array. Write a main to test all these functions.
#include<iostream>
usingnamespace std;
int main()
{
int p, n = 4, val;
int *array = newint [n];
for (int i=0; i<4; i++)
cin>>array[i];
while(1)
{
cout<<"Enter 0 to end and 1 to continue";
cin>>p;
while(1)
{
cin>>val;
append(array,val,n);
}
}
return 0;
}
I do not know how to proceed further. Please give me a hint or tell me how shall I do this?
def append(value, array, size, capacity):
if size == capacity: //is full
capacity *= 2
aux = new Type[capacity] //allocate a new region, duplicate the capacity
copy_n(array, size, aux) //copy the vales
delete [] array //deallocates old region
array = aux //point to new location
//add the value
> Just use globals for array, maxsize, and usedsize.
> I don't know if that'll lose you points, though. It would in my class.
¿so why are you suggesting them?
As far as using globals, for this learning purpose, it appears the professor expects the students to learn to do stuff, and will later package it properly. One concept at a time.
and then you need to work with two vectors and the global code crumbles
> I suggested not referring to them directly.
¿so you mean to pass them to this function? void append( int* &array, int &maxsize, int &usedsize, int value );
¿what's the point on making them global then?
by the way, `malloc()' and `realloc()' allocates n bytes, so malloc( new_size + 1 ); will may not give you enough for another integer.