New keyword in C++
New Operator in C++
New keyword in C++ is a very helpful way to improve a program. In case of static memory allocation once the memory is allocated it cannot be deleted and unused memory gets wasted whereas dynamic memory allocation
enables the programmer to manually create and delete (give back to store) the memory at any point of time
New keyword in C++
Dynamic Memory Allocation: The advantage of dynamic memory mechanism used to locate memory at the time of execution without any wastage of memory block.
In C++ dynamic memory concept is supported by new
and delete
operators, here we will discuss the new keyword in C++ in detail.
New: The new operator allocates the required bytes of memory by returning a pointer to the allocated memory
Syntax
datatype *varname=new datatype[size]
Example
int *p =new int[7] //14 bytes= 7 *2 bytes
- For example, if the size of the integer is 2, 14 bytes of memory is returned by the new operator for n specified as 7
- initially pointer variable p contents of base address i.e first byte of memory
C++ program to create memory dynamically to store some data and display the data
#include <iostream> using namespace std; int main() { int *p, i, n; cout << "enter the size:"; cin >> n; p = new int[n]; //allocates n*sizeof(int) bytes if (p == NULL) //in rare case if available memory not available { cout << "\nmemory alloacation failed"; exit (1); } cout << "\nenter the elements\n"; for (int i = 0; i < n; i++) { cin >> *(p + i); } cout << "elements are:\n"; for (int i = 0; i < n; i++) { cout << *(p + i) << "\t"; } return 0; }
Output
Enter the size 5 Enter the elements 1 6 0 8 3 Elements are: 1 6 0 8 3
Heap memory
Dynamic memory allocation always takes place in a memory area calledheap
, because heap Data Structure has a property to grow and shrink at any point of time i.e memory can be deleted and allocated at any point of time as per the requirement. Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment