Reputation: 3894
I create an array like as below
int size = 5;
double my_arr[m_size];
for (int i = 0; i < size; i++)
{
my_arr[i] = (rand()%10+1) + ((double) rand() / (RAND_MAX));;
}
after doing some calculation on array I want to delete the array. So I do this
for (int i = 0; i < size; i++)
{
delete my_arr[i];
}
and I get this error
error: type ‘double’ argument given to ‘delete’, expected pointer
I searched internet and all solutions are related to pointer array. But I am not using any pointer. So how can I delete this array?
Upvotes: 0
Views: 964
Reputation: 168
First of all, I think you should consider using a memory leak detector in your programms, so you can know by yourself if your code is leaking and if you have to do something about it. In your code you would have seen that there is no need to delete anything. :)
As far as I know, you should worry about memory in only two cases:
malloc
or calloc
. In this case, you need to use the function free
to deallocate the array. But generally in C++, you don't want this. You prefer using a container like std::array
or std::vector
instead.new
and you have got a pointer to this instance. In this case, you have to use delete
on the pointer when you don't need this instance anymore. But generally in C++11 (or further), you don't want this. If you really have to use a pointer, you prefer creating a smart pointer like std::unique_ptr
or std::shared_ptr
which will handle the memory for you.When you define a variable without using new
, malloc
or calloc
, (for example int a = 1 ;
), it will be automatically deleted when it goes out of scope. So you don't need to worry.
Here is a simple example of a variable going out of scope:
int a = 1 ;
{
int b = 1 ;
// b is implictly deleted here, just before the bracket.
}
a++; // It works, because a exists in this scope
b++; // It doesn't work, because b is out of scope.
// a is implicitly deleted here, assuming we are at the end of a function
Upvotes: 0
Reputation: 181
The array will be automatically deleted when leaving the scope in which the variable has been declared. If you really need to free memory fast you can try put your code between embraces:
{ //create new scope
int size = 5;
double my_arr[m_size];
for (int i = 0; i < size; i++)
{
my_arr[i] = (rand()%10+1) + ((double) rand() / (RAND_MAX));;
}
//some stuff
} //all non-pointer objects (or arrays) will be deleted
Or you can use pointers :
double *pMyarr = new double[m_size] ;
Upvotes: 3