Allocate and free memory dynamically - C++

Q. Write a C++ program to allocate memory dynamically for an integer, initialize it to 10 and free that memory.

Answer:

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    int i, *ptr;

    ptr = (int*) malloc(10 * sizeof(int));  //memory allocated using malloc
    if(ptr == NULL)                     
    {
        cout<<"\n Error! memory not allocated.";
        exit(0);
    }
    cout<<"\n Enter 10 Integer Numbers : \n";    
    for(i = 0; i < 10; ++i)
    {
        cout<<" ";
        cin>>ptr[i];
        
    }   
    cout<<"\n Displaying Integer Numbers : \n";
    cout<<" ------------------------------- \n";
    for(i = 0; i < 10; ++i)
    {
        cout<<" ";
        cout<<ptr[i];
        cout<<"\n";
    }
    free(ptr);
    return 0;
}


Output:

dynamic allocation ten integers