Search code examples
c++dynamic-arrays

c++, minify dynamic array by delete [] x[i]


I have a 2D array with size 4 (4 rows). To make the array size 2 (2 rows), can I use following? (for our hw assignment details are not specified and the code should be suitable with common c++ standarts)

I am removing second half of the array.

const int newSize = flightsArraySize/2;
for(int i = newSize-1; i < flightsArraySize-1; i++)
   delete [] flights[i];

Or do I have to recreate flights array with size 2?


Solution

  • Supposing that you have created a 2D array using new like this:

    int **arr = new int*[rows];
    for(int i=0; i<rows; ++i)
        arr[i] = new int[cols];
    

    Then to resize it you'd have to do something like:

    int newRows = rows/2;
    
    // Create a new array for the right number of rows.
    int **newArr = new int*[newRows];
    
    // Copy the rows we're keeping across.
    for(int i=0; i<newRows; ++i)
        newArr[i] = arr[i];
    
    // Delete the rows we no longer need.
    for(int i=newRows; i<rows; ++i)
        delete[] arr[i];
    
    // Delete the old array.
    delete[] arr;
    
    // Replace the old array and row count with the new ones.
    arr = newArr;
    rows = newRows;
    

    But seriously, this is all so much easier if you just use vector:

    std::vector<std::vector<int>> v(rows);
    for(int i=0; i<rows; ++i)
        v[i].resize(cols);
    v.resize(v.size()/2);