Declaring an Integer Variable using new operator in C++ programming.
In C++, new is an operator which is used to declare memory at run time i.e. it is used for Dynamic Memory Allocation. This code snippet will declare and free memory for an integer variable using new and delete operators.
C++ Code Snippet - Declaration of an Integer Variable using new Operator
/*Declaring an integer variable using new.*/
#include <iostream>
using namespace std;
int main()
{
/* integer pointer declaration,
to store address of dynamically allocated memory*/
int *ptr;
/* Declare memory for an int variable
using new operator*/
ptr=new int;
/* Assign value to pointer*/
*ptr=10;
/* Printing address and value*/
cout<<"value is: "<<*ptr<<", address is: "<<ptr<<endl;
/* Free dynamically allocated memory*/
delete ptr;
return 0;
}
value is: 10, address is: 0x13fb010