Sunday 25 April 2021

Dynamic Array in C++



class A







 void show()









int main()




int *a=new int(5);


int *A=new int[5];



/*for(int i=0;i<5;i++)





cout<<A[i];    */

delete a;


delete[] A;

//delete A[1];   Error

delete [1]A;




return 0;


delete operator

Compiler did not automatically deallocate dynamically allocated memory, If we want to delete dynamically allocated memory, we must deallocate it manually using delete operator.


// Release memory pointed by pointer-variable

delete pointer-variable; 

For example

int *p=new int;  //dynamically allocated memory

int *q = new int(5);  //dynamically allocated memory

delete p;  //dynamically deallocated memory

delete q;   //dynamically deallocated memory

The delete operator deallocates memory and calls the destructor for a single object created with new.

delete [] 

To free the dynamically allocated array pointed by pointer-variable, use following form of delete:

// Release block of memory pointed by pointer-variable


delete[] pointer-variable; 


   // It will free the entire array pointed by p.

 delete[] p;

for example

int *p = new int[5];

delete [] p;


delete [size] p;  

delete [5] p;

We can use any value for size. It will delete the entire array. but delete [size] p is not working in many compiler. So always use delete [] p;  without size.

1.      The delete [] operator deallocates memory and calls destructors for an array of objects created with new []. 

2.      The delete[] operator is used to delete arrays. The delete operator is used to delete non-array objects.

3.      delete is used to de-allocate memory allocated for single object

4.      delete[] is used to de-allocate memory allocated for array of objects



Deleting the array just tells the heap manager that that area of memory once again available for use in the future. It doesn't immediately overwrite the memory. It does, however, mean that the area might get overwritten at any time. So you aren't allowed to rely on its contents anymore. Content of array may be same as before the delete operator and after the delete operator. The memory is free, which means it isn't attributed anymore, but the compiler's not going to take the extra effort to wipe it back to 0 every time something's deleted.

Default value of elements in dynamically allocated array is 0.

No comments:

Post a Comment