Declare a dynamic array and write Resize functions which resizes array in such a way that it retains old data and discards overflow data if new size is smaller.
#include <iostream>
using namespace std;
template <typename T>
T* resize(T* arr, int oldSize, int newSize)
{
T* newArr = new T[newSize];
for (int i = (oldSize < newSize ? oldSize : newSize) - 1; i >= 0; --i)
{
newArr[i] = arr[i];
}
delete[] arr;
return newArr;
}
int main()
{
char* c = new char[10] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
c = resize(c, 10, 5);
for (int i = 0; i < 10; ++i)
{
cout << c[i];
}
return 0;
}
Comments
Leave a comment