If i increment the pointer and pass it to function why it prints address after returning to main?? | Sololearn: Learn to code for FREE!
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.

27th Dec 2018, 2:56 PM
Rohit
Rohit - avatar
4 Answers
+ 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.
27th Dec 2018, 3:51 PM
Dennis
Dennis - avatar
+ 2
It's Undefined Behaviour! Warning
27th Dec 2018, 6:13 PM
AZTECCO
AZTECCO - avatar
0
Weird, if i run the same code in another app, i get a diffrent output than here on sololearn
27th Dec 2018, 3:50 PM
CodeMStr
CodeMStr - avatar
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
27th Dec 2018, 4:15 PM
Calviղ
Calviղ - avatar