Introduction
Both malloc() and new in C++ are used for the same purpose. They are used for allocating memory on the runtime. But, malloc() and new have unique syntax. The principal distinction between the malloc() and new is that the new is an operator even as malloc() is a standard library function predefined in a stdlib header file.
Also, see Literals in C.Fibonacci Series in C++
What is new?
- The new is a memory allocation operator used to allocate the memory on the runtime. The memory initialized through the new operator is allotted in a heap. It returns the beginning address of the memory, which is assigned to the variable.
- The functionality of the new operator is much like the malloc() characteristic, which turned into used withinside the C programming language.
- C++ is well suited with the malloc() characteristic also. However, the new operator is generally used due to its advantages.
Syntax of new() operator:
type variable = new type(parameter_list);
C++ code to represent the new operator:
#include <iostream>
using namespace std;
int main() {
// integer type pointer variable declaration .
int * p;
// memory allocation to the pointer variable p.
p = new int;
cout << "Enter the number : " << endl;
cin >> * p;
cout << "Entered number is " << * p << endl;
return 0;
}
Input:
20
Output:
Enter the number :
Entered number is 20
You can try and compile with the help of online c++ compiler. You can also do a free certification of Basics of C++.