Wednesday, 20 August 2014

Dynamic memory allocation in c++ using calloc/malloc and realloc.

#include<iostream>
#include<stdlib.h>
using namespace std;
main()
{
    int *arr,m,n,i;
    cout<<"Enter total no. of elements:";
    cin>>n;
    arr=(int *)malloc(n*sizeof(int));
    cout<<"\nEnter "<<n<<" elements:";
    for(i=0;i<n;i++)
    {
        cin>>*(arr+i);
    }
    cout<<"Enter another total no. of elements:";
    cin>>m;
    arr=(int *)realloc(arr,m*sizeof(int));
    cout<<"Enter another "<<m<<" elements:";
    for(i=n;i<m+n;i++)
    {
        cin>>*(arr+i);
    }
    cout<<"\nThe elements are:";
    for(i=0;i<n+m;i++)
    {
        cout<<"\t"<<*(arr+i);
    }
    free(arr);
}

No comments:

Post a Comment