• Advertisement
Sign in to follow this  

[Help] delete dynamic array

This topic is 3194 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

        int *aa;
	aa=NULL;
	int num=2;
	aa=new int[2];
	aa[0]=1;
	aa[1]=2;
	aa[2]=3;
	cout<<aa[2]<<endl;
	delete[] aa;
	system("pause");

last second line is delete an dynamic array right? but i got an error picture_here

Share this post


Link to post
Share on other sites
Advertisement
aa=new int[2] creates an array of length 2 - a[0] and a[1]. You then access a[2], which would be the third element, hence your crash.

It's the classic confusion with counting from zero - your last valid array index is always one less than the size of the array.

Share this post


Link to post
Share on other sites
You allocate a vector with two elements but then write to a third element. The debug runtime detects that you have written beyond the boundaries on the call to delete and raises the warning you see.

Share this post


Link to post
Share on other sites
Quote:
Original post by tomneo2004
ok thanks guys but if i change int type to the type that define by myself is it possible to use delete[] to clear array?
No, delete[] will destruct elements and deallocate the array. It is possible to override the new and delete operators but clearing arrays is still not what they're for.

I recommend you look into using std::vector instead, for one thing this can clear itself.

Share this post


Link to post
Share on other sites
Quote:
Original post by tomneo2004
ok thanks guys but if i change int type to the type that define by myself is it possible to use delete[] to clear array?

What exactly do you mean by "clear"? After delete[], the array won't exist anymore.

Share this post


Link to post
Share on other sites
Quote:
Original post by dmatter
I recommend you look into using std::vector instead, for one thing this can clear itself.

Excellent suggestion. The program would then look like this:

#include <iostream>
#include <vector>

int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
std::cout << vec[2] << std::endl;
}


Note the abscence of manual memory management. No more new[] and delete[], and you don't have to worry about how large the vector needs to be.

Share this post


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

  • Advertisement