Question #186278

Explain about new and delete keywords with code.


Expert's answer

/*
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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS