Your function is not implemented correctly, not even close.
You should not be allocating a new array every time the function is called, only when the current array is not large enough to store the user's number.
If count
and size
are not the same value, you are leaking memory, and you are not inserting anything into the existing array.
You are touching the array only if count
and size
are the same value, but when you go to store the user's number into the new array, you are storing it at the wrong index.
Try this instead:
void add_element(int* &array, int &size, int &count)
{
int number;
cout << "What number do you want to add? " << endl;
cin >> number;
if (count == size)
{
int newSize = size * 2;
int *newArr = new int[newSize];
for (int i = 0; i < count; ++i)
{
newArr[i] = array[i];
}
delete[] array;
array = newArr;
size = newSize;
}
array[count] = number;
++count;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…