0
0
C++programming~5 mins

new operator in C++

Choose your learning style9 modes available
Introduction

The new operator helps you create variables or objects in memory while your program is running. It lets you ask for space to store data when you need it.

When you want to create a variable but don't know how many you need until the program runs.
When you want to keep data even after a function ends.
When you want to create objects that live until you decide to remove them.
When you want to manage memory yourself for better control.
When you want to create arrays with sizes decided during the program.
Syntax
C++
pointer_variable = new data_type;
pointer_variable = new data_type[size];

The new operator returns a pointer to the memory it allocates.

Remember to use delete or delete[] to free memory later.

Examples
Creates a single integer in memory and p points to it.
C++
int* p = new int;
Creates an array of 5 doubles in memory and arr points to the first element.
C++
double* arr = new double[5];
Creates a single char initialized with 'A'.
C++
char* c = new char('A');
Sample Program

This program creates one integer and an array of three integers using new. It stores values, prints them, and then frees the memory with delete and delete[].

C++
#include <iostream>

int main() {
    int* num = new int;          // create one int
    *num = 42;                  // store 42 in it

    int* arr = new int[3];      // create array of 3 ints
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;

    std::cout << "Single number: " << *num << "\n";
    std::cout << "Array elements: ";
    for (int i = 0; i < 3; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";

    delete num;                 // free single int
    delete[] arr;               // free array

    return 0;
}
OutputSuccess
Important Notes

Always pair new with delete to avoid memory leaks.

Use delete[] for arrays created with new[].

Access the allocated memory through the pointer returned by new.

Summary

new creates variables or arrays in memory during program run.

It returns a pointer to the allocated memory.

Always free memory with delete or delete[] when done.