Advertisement
//C++ Example of new operator to create a variable
#include<iostream>
using namespace std;
int main()
{
//Creating an int variable by using the new operator
int *p = new int;
//Initializing the newly created int variable
*p = 10;
cout<< "The int value at the address pointed by pointer variable : " << *p << "\n";
cout<< "The memory address allocated to pointer variable : " << p;
//Creating and initializing a float variable using the new operator in a single line
float *f = new float(10.5);
cout<< "The float value at the address pointed by pointer variable : " << *f << "\n";
cout<< "The memory address allocated to pointer variable : " << f;
return 0;
}
The int value at the address pointed by pointer variable : 10
The memory address allocated to pointer variable : 0x6f1690
The float value at the address pointed by pointer variable : 10.5
The memory address allocated to pointer variable : 0x6f0f48
//Creating and initializing a float variable using new operator in a single line
float *f = new float(10.5);
Advertisement
//C++ Example of new operator to create an array object
#include<iostream>
using namespace std;
int main()
{
//Creating a memory space for a char array with 5 elements, using new operator
char *arr = new char[5];
arr[0] = 'a';
arr[1] = 'b';
arr[2] = 'c';
arr[3] = 'd';
arr[4] = 'e';
cout<< "The multiple char values in the char array: \n";
for(int i=0;i<5;i++)
{
cout<< arr[i] << "\n";
}
cout<< "The memory address allocated to pointer variable : " << arr;
return 0;
}
The multiple char values in the char array:
a
b
c
d
e
The memory address allocated to pointer variable : abcde
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement