C++ 42:Dynamic Memory Management

  • Dynamic means runtime(i.e. when the program is executing its execution is not finished).
  • Dynamic memory management means reserving and relesing memory during the runtime.
  • To reserve the memory at runtime we can use new and delete operators. 
new - The new operator is used to reserve a memory block for specified datatype and return the starting and the ending address of the reserved memory. 
Syntax: pointer_name = new data_type(size);

delete - The delete operator is used to instructs he operating system ti relese the memory block which was reserved by using new operator.
Syntax: delete pointer_name;

Example:
WAP to read N numbers and find there sum and mean

#include <iostream>
using namespace std;

int main()
{
    int N;
    cout << "How many digits did you want to add?:  ";
    cin >> N;

    int *ptr = new int[N]; //Runctime memory reservtion

    cout << "Enter " << N << " Integers: ";
    for (int i = 0i < Ni++)
    {
        cin >> *(ptr + i);
    }

    int sum = 0;
    for (int i = 0i < Ni++)
        sum = sum + *(ptr + i);

    cout << "\nSum is: " << sum << endl;

    return 0;

}

Output:

Enter 4 Integers: 24 2 3 1
Sum is: 30




Comments

Popular posts from this blog

C++ 38: Visibility Modes Public, Private and Protected