problem with deallocation

Started by
2 comments, last by Watchman234 16 years, 9 months ago
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?
Advertisement
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?
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 3for( int i = 0 ; i < x.size() ; ++i ) { x = i; }x.erase( x.begin() + 1 );
ok , thanks.

This topic is closed to new replies.

Advertisement