0
If i increment the pointer and pass it to function why it prints address after returning to main??
int main() { int i=10, *p=&i; foo(p++); cout << *p; } int foo(int *p) { cout << *p; } Here when i run the program i get o/p as 10 and when it comes back to main some address is printed.
4 odpowiedzi
+ 4
The original value of p is passed to foo and incremented after that.
In foo p is still pointing to i and prints the expected value 10.
Back in the main function p is now pointing to an address 4 bytes after i which contains garbage.
+ 2
It's Undefined Behaviour! Warning
0
Weird, if i run the same code in another app, i get a diffrent output than here on sololearn
0
I modified your code to make pointer points to an array, hopefully you could understand what have happened. Please read the code comments.
int main()
{
int i[2]={10, 20}, *p;
p = i;
cout << "*p = " << *p << endl; // *p = 10
foo(p++); // p is the input parameter
cout << "*p = " << *p << endl; // p now only increment to p+1, so *p not 10, but next value 20
return 0;
}
int foo(int *p)
{
cout << "foo *p = " << *p << endl;
}
https://code.sololearn.com/cObwr4Wcr92u/?ref=app