Вы передаете значение arr
как указатель, а не как ссылку.Мы можем изменить resize
для передачи указателя по ссылке, просто добавив &
:
// Passes the pointer to 'arr' by reference
void resize(int*& arr, int size, int yes )
{
int *newA = new int[size+1];
for( int i=0; i<size; i++ )
{
cout << arr[i];
newA[i] = arr[i];
}
delete [] arr;
newA[size] = yes;
arr = newA;
}
При этом в стандартной библиотеке есть встроенный класс, который уже делает это!Он называется std::vector
, и он хорошо собран, так же быстро, как обычный массив (когда вы компилируете с оптимизацией), и он автоматически удаляет всю память, которую он выделяет!
С std::vector
, исходный кодвыглядит так:
int main()
{
std::vector<int> arr(5); // Create a vector with 5 elements
// Assign them
for(int i=0; i<5; i++ )
arr[i] = i;
// Print them
for( int i=0; i<5; i++ )
cout << arr[i];
cout << endl;
// add the number 5 at the end of arr
// resize happens automatically
arr.push_back(5);
// The number 5 now appears at the end of the array
for( int i=0; i<6; i++ )
cout << arr[i] << endl;
cout << endl;
return 0;
}