ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Declaring an Integer Variable using new operator in C++ programming.


IncludeHelp 13 June 2016

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

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.