How to Use Dynamic Memory in C++

Dynamic Memory means your program allocate memory according to the need. In complicated problems memory has big concern and programmers can't assign static memory. New operator is used to allocated dynamic memory. A data type is required for new to followed it. In this problem a dynamic array will be create according to the user input.

Source Code

#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,nums;
  int * p;
  cout << "How many numbers would you like to Enter ";
  cin >> nums;
  p= new (nothrow) int[nums];
  if (p == 0)
    cout << "Error! memory could not be allocated";
  else
  {
    for (int i =0; i < nums; i++)
    {
     cout << "Enter number: ";
     cin >> p[i];
    }
    cout<<endl;
    cout << "You have entered: \n ";
    for (int i =0; i <nums; i++)
    cout <<endl<< p[i];
    delete[] p;
  }
  return 0;
}

Output of the Program

Dynamic Memory in C++

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment