Sign in to follow this  
Watchman234

problem with deallocation

Recommended Posts

Watchman234    122
I`m trying to deallocate the address of one array`s index and a runtime error occured :(. here is the code i have tried to compile: int *x = new int[3]; x[0] = 1; x[1] = 2; x[2] = 3; delete (x+1); I dont understand why its not working , can`t i just delete one index of the array?

Share this post


Link to post
Share on other sites
Gage64    1235
When you call delete on an address of an object that was allocated with new, that address has information required to do the deallocation properly (or rather, the compiler knows how to get that information given the address). What you are calling delete on is not such an address.

Also, when an array is allocated, it is allocated as one big chunk of memory. You can't delete just a part of that chunk. Why do you want to delete just "one index" anyway?

Share this post


Link to post
Share on other sites
rip-off    10976
Quote:
Original post by Watchman234
I`m trying to deallocate the address of one array`s index and a runtime error occured :(.
here is the code i have tried to compile:

int *x = new int[3];
x[0] = 1;
x[1] = 2;
x[2] = 3;
delete (x+1);

I dont understand why its not working , can`t i just delete one index of the array?


Nope. You can only pass to delete what you got from new, and to delete [] what you got from new [].

However, you would be better served by using a container class like std::vector:

#include <vector>

std::vector x(3); // vector with initial size 3
for( int i = 0 ; i < x.size() ; ++i ) { x[i] = i; }
x.erase( x.begin() + 1 );

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this