0

I want to dynamically allocate memory for an array and read some input data for it, like this:

void citire(int& a, int* array)
{
    std::cin >> a;
    array = new int[a];
    for (int i = 0; i < a; i++)
    {
        std::cin >> array[i];
    }
}

Then I want to remove N values from the array, starting with startingPos:

int scoatereNumarDePozitiiDinVector(int& a, int* array, int n, int startingPos)
{
    for (int i = startingPos; i < n; i++) //n is how many positions I want to delete
    {
        array[i - n] = array[i];
    }
    for (int i = n-1; i > n-startingPos; i--)
    {
        delete(array[i]);
    }
    a -= n;
}

But I get two errors:

"delete" - cannot delete objects that are not pointers
expression must be a pointer to a complete object type

How can I make it work? I can just shrink a (which is the length of the array), but I'd like to really make the array smaller if there is something deleted.

Thanks.

  • You can not, array size is fixed. Also you should only invoke `delete` on pointer received as result of invoking `new`. – user7860670 Feb 25 '21 at 11:46
  • 3
    You should use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector), which has [`shrink_to_fit()`](https://en.cppreference.com/w/cpp/container/vector/shrink_to_fit). – MikeCAT Feb 25 '21 at 11:47
  • Also note that your `citire` function causes memory leak by not saving the pointer `array` before returning from the function. – MikeCAT Feb 25 '21 at 11:48

0 Answers0