Here, you have declared a variable called ptr
void question1() { int i=0; int* ptr=nullptr;
Here you are declaring a completely different variable, which also happens to be called ptr
and hides the variable you'd previously declared by the same name.
while(boolean!=false) { cout << "Enter number: " << endl; int* ptr=new int[i+1];
Since this new ptr
variable is declared inside your loop, it is destroyed at the end of your loop, and the new int[]
memory which you'd allocated is being leaked, since there are no other references to it in your program.
I'd suggest renaming one of your 'ptr' variables, and being careful to ensure that the memory you're allocating is properly tracked, and also deleted when you no longer needed. (Note, memory allocated using new[] needs to be cleaned up with delete[] - don't omit the subscript []
operator)
Alternatively, a smarter way to do this (without new/delete) would be to avoid yucky stuff like pointers and new/delete, then to replace it with a vector (which is a resizable "C++ array")
#include <vector>
// ... etc.
vector<int> temp;
bool boolean=true;
while(boolean!=false)
{
cout << "Enter number: " << endl;
int n;
cin >> n;
if(n!=-1)
{
temp.push_back(n);
}
else
{
for(int j = temp.size() -1 ; j>=0; j--)
{
cout << temp[j] << " " ;
}
boolean = false;
}
}