When while and cin involved , this question becomes so vague to me .
If I don't use cin or anything else here ,just new int and pointers , everything is fine !
Help me understand please ,thanks :)
#include <iostream>
usingnamespace std;
int main()
{
int *p = newint ; //somewhere on the heap
int temp ;
while (cin >> temp) /*this overloaded operator returns istream object ,
where is it stored ? How do I know its accurate address ?*/
{
*p = temp ;
p ++ ; // arbitrary times loops , break the loop using Ctrl + Z on Windows
}
p--; // move pointer to the last memory location which has valid value.
cout << *p ; //why it points to garbage ?
delete p ; //destroy the pointer on the stack .
}
12
23
121
21
7
^Z
7 //This is a sample input and output using my code :
Process returned 0(0x0) ...
//Weird ...it works perfectly again ....
@ne555 ,Are you from Spain or Latin American ? I love the upside down ? ,Haha .
I input 5 ~ 10 numbers usually . but this time it turned out to be okay ,I am even more confused .....:(
This program should print out the last number you entered .
this overloaded operator returns istream object ,
where is it stored ? How do I know its accurate address ?
It returns the provided istream left of the operator >>. In this case cin. So it is absolutely reliable.
When you modify p (p++ / p--) it will be out of bounds because you provided only memory for a single int. So any access to a value of p that is not the original value will lead to undefined behavior / probably crash.