+ 1
How i understand this.
1 void myFunc(int *x) { 2 *x = 100; 3 } 4 5 int main() { 6 int var = 20; 7 myFunc(&var); 8 cout << var; 9 } 10 // Outputs 100 in line 7 the address of var is passed to line 1 parameter which implies that int *x is assigned the value of var. but in line 2 *x is given another value that is 100. so *x has two values now. that is 100 and address of var. plis make correction if i m wrong
2 Answers
+ 10
I don't blame you for being confused - this is a complicated concept! Think of it this way - & and * work together. & fetches the address of a variable. * points to that variable when you give it an address you got with &.
You got lines 7 and 1 correct - var's address is being passed to myFunc(), and stored in a pointer that can use that address. It's like you told myFunc() "var is here! You can use it and change it!"
When you assign 100 to *x, what you're really doing is assigning 100 to var, which *x is pointing at. And when myFunc() ends, var will still be 100.
The only way to reassign a pointer itself is to give it a new address to point at with &.
+ 2
https://code.sololearn.com/cIxFf27nurVi ; it may help just check