+ 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

13th Jul 2017, 3:23 AM
stephen haokip
stephen haokip - avatar
2 Respuestas
+ 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 &.
13th Jul 2017, 3:40 AM
Tamra
Tamra - avatar
+ 2
13th Jul 2017, 1:16 PM
Melih Melik Sonmez
Melih Melik Sonmez - avatar