0
0
C++programming~5 mins

Why dynamic memory is needed in C++

Choose your learning style9 modes available
Introduction

Dynamic memory lets a program get more memory while it runs. This helps when you don't know how much memory you need before the program starts.

When you want to store a list but don't know its size in advance.
When you need to create objects during the program based on user input.
When you want to use memory efficiently and only allocate what you need.
When working with data that changes size, like growing arrays or linked lists.
Syntax
C++
int* ptr = new int; // allocate memory for one int
int* arr = new int[size]; // allocate memory for an array

// When done, free memory:
delete ptr;
delete[] arr;
Use new to get memory from the heap during runtime.
Always use delete or delete[] to free memory and avoid leaks.
Examples
Allocates memory for one integer, stores 10, prints it, then frees the memory.
C++
int* p = new int; // allocate one int
*p = 10;
std::cout << *p << std::endl;
delete p;
Creates an array of 5 integers, fills it with even numbers, prints them, then frees the array.
C++
int size = 5;
int* arr = new int[size];
for(int i = 0; i < size; i++) {
    arr[i] = i * 2;
}
for(int i = 0; i < size; i++) {
    std::cout << arr[i] << ' ';
}
std::cout << std::endl;
delete[] arr;
Sample Program

This program asks the user how many numbers they want to store. It then creates a dynamic array of that size, fills it with numbers from 1 to n, prints them, and frees the memory.

C++
#include <iostream>

int main() {
    int n;
    std::cout << "Enter number of elements: ";
    std::cin >> n;

    int* numbers = new int[n];

    for(int i = 0; i < n; i++) {
        numbers[i] = i + 1;
    }

    std::cout << "Numbers: ";
    for(int i = 0; i < n; i++) {
        std::cout << numbers[i] << ' ';
    }
    std::cout << std::endl;

    delete[] numbers;
    return 0;
}
OutputSuccess
Important Notes

Dynamic memory is stored on the heap, which is different from fixed memory on the stack.

Always free dynamic memory to prevent memory leaks, which can slow down or crash programs.

Summary

Dynamic memory allows programs to use memory flexibly during runtime.

It is useful when the amount of data is not known before running the program.

Remember to free dynamic memory to keep your program healthy.