[Solved] How do I create a new array and copy the last elements of the old array into the new array while the new array is smaller?


Works for me

void resize(double *&a, int oldSize, int newSize) {
    double *a1 = new double[newSize]();
    if (newSize > oldSize) {
        for (unsigned i = 0; i < oldSize; i++) {
            a1[i] = a[i];
        }
    }
    else if(oldSize > newSize) {
        for (unsigned i = 0; i < newSize; i++)
        {
        a1[i] = a[oldSize - newSize+i];
        }
    }

    delete [] a;
    a = a1;
}

25 first size; 10 last elements;

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

16 17 18 19 20 21 22 23 24 25

2

solved How do I create a new array and copy the last elements of the old array into the new array while the new array is smaller?