1

Im trying to understand pointers, below my code:

int main()
{

    int size = 5; //Size of array
    int position = 2; //Position to delete

    int *pointer = new int[size]; //Pointer declaration

    //Populates array with numbers starting at 1 up to size elements (5 in this case)
    for (int i = 0 ; i < size; i++)
    {
        pointer[i] = i+1;
    }

    //Prints existing elements (numbers 1 to 5 in this case)
    for (int i = 0 ; i < size; i++)
    {
        std::cout << pointer[i] << ", ";
    }


    return 0;
}

I know that if I do delete [] pointers; it will delete the array from the memory, but how can I delete just the object inside position 2 or resize the array?

1 Answer 1

2

You can't do either of those things. You can move items around within your existing allocation, and you can make a new allocation, copy items over, and delete the old allocation.

To work with data you should use a container called vector which provides member functions to remove an element or resize. A vector is the equivalent in C++ of what most other languages call an "array".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your fast response. I know how to do it with vectors, i was just trying to "resize" the pointer array without copying the elements that i don't want to delete to a new allocation and then deleting the old allocation (this is the way vectors do it if i am not mistaken).
Apparently that is the only way you can do it. Thanks again.
Yes, vectors do that. However vectors also allocate more than you're currently using (called the capacity), and remember how many items are in use via size. So if you are resizing by a small amount it does not need to do another allocation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.