Answer to Question #190757 in C++ for Nadeem Shah

Question #190757

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.


1
Expert's answer
2021-05-08T09:15:24-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment