Explain about new and delete keywords with code.
/*
C++ new keyword is used to allocate memory to a variable. The new operator returns the address of the memory location.
The delete keyword is used to deallocate the memory.
*/
#include <iostream>
using namespace std;
int main()
{
// declare an int pointer
int* ptrInt;
//Dynamically allocate memory using new
ptrInt = new int;
//assigning value to the memory
*ptrInt = 100;
cout << *ptrInt << endl;
//deallocate the memory using delete
delete ptrInt;
//Will display 0
cout << *ptrInt << endl;
return 0;
}
Comments
Leave a comment