delete[] operator

1
2
3
int *a = new[2];
a[0] = 2;
a[1] = 3;

how to delete single element on an dynamic allocated array?
delete[1]a; // its not working

also can you show me a code which, if i delete a dynamic allocated variable,
the next variable stores to it will be deleted as well.

You cannot delete a part of array. You can however have a variable denoting logical sise of array and move "deleted" values to the end of array:
1
2
3
4
5
6
7
8
9
10
11
#include <algorithm>
#include <iostream>

int main()
{
    int* arr = new int[5] {1, 2, 3, 2, 1};
    int* end = arr + 5;
    end = std::remove(arr, end, 2);
    for(int* i = arr; i != end; ++i)
        std::cout << *i << ' ';
}
1 3 1 
http://coliru.stacked-crooked.com/a/69cfe7a5f4f3f24b

Or use std::vector whic has erase function and allows to delete any value containing in it.
Last edited on
move "deleted" values to the end of array:

but that does not free any memory up does it?
No. Why would you want it in this case?

If you want, you can create new array, copy values you need from old array and delete old array. However in your case it will actually waste memory: I doubt those 16 bytes will be ever allocated again. And if you need to add values, you will need to reallocate array again, when in logical/physical size approach you will have some kind of buffer memory you can use before you have to reallocate.

Consider using vectors:
1
2
3
4
5
6
7
std::vector<int> v {1, 2, 3, 2, 1}; //Create vector
std::cout << v.size() << '\n'; //No need to remember actual size. Vector knows it itself
v.erase(std::remove(v.begin(), v.end(), 2), v.end()); //Erase-remove idiom
for(int i = 0; i != v.size(); ++i ) 
    std::cout << v[i] << ' ';
std::cout << '\n' << v.size() << '\n';
v.shrink_to_fit(); //If you so concious about those several bytes of memory.
5
1 3 1 
3
Topic archived. No new replies allowed.