I am new to C++ and is learning about dynamic memory allocation. I wrote a code to learn the use of "new" operator but is having problem with the output.
Here's the basic code which i wrote:
#include<iostream>
#include<new>
using namespace std;
main()
{
int *p,i,m;
cout<<"how many values u want to insert?"<<"\n";
cin>>i;
cout<<"\n";
p=new (nothrow) int[i];
if(p == 0)
cout << "Error: memory could not be allocated";
for(m=0;m<i;m++)
{
cout<<"Insert value no."<<m+1<<" :\n";
cin>>p[m];
cout<<"\n";
}
for(m=0;m<i;m++)
{
cout<<"Ur value no."<<m+1<<" is: "<<p[m]<<"\n";
delete [] p;
}
}
The problem with the output is that the second value returns garbage. For ex: if the user enters that they want to insert 3 values with inputs 5,6 and 7 as the three values the outputs are 5, 84569712 and 7. I am unable to understand why the 2nd value is so abrupt. Help me with this please.
Below is the link of output image file: https://www.dropbox.com/s/54qfh1kmzq37ypi/output%20image.PNG