Jump to content
  • Advertisement
Sign in to follow this  
Watchman234

problem with deallocation

This topic is 4031 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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?

Share this post


Link to post
Share on other sites
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; }
x.erase( x.begin() + 1 );

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!