+ 1

Why is the ouput 100

// so I got lost a little we outputted var and I was in mere shock to see that it was 100. I don't get why it's not 20? (can someone please explain it to me thank you so much (^_^) ) void myFunc(int *x) { *x = 100; } int main() { int var = 20; myFunc(&var); cout << var; } // Outputs 100

8th Apr 2019, 4:31 AM
Gideon Adams
Gideon Adams - avatar
3 Answers
+ 5
var gets modified inside myFunc(). *x is basically equal to var. x is a pointer to var. In other words, x contains the address of var. When x is dereferenced *x is the same as var.
8th Apr 2019, 4:40 AM
Sonic
Sonic - avatar
+ 2
Pointers contain addresses of variables. When you pass a variable as a pointer to the function, what gets passed over to the function is actually the memory address of the original variable in main. You alter the value of what is stored in the memory address, and as a result, the variable in main will reflect the changes you made to the value stored in that particular memory address.
8th Apr 2019, 4:35 AM
Fermi
Fermi - avatar
+ 1
thank you so much Fermi and Sonic (^_^)
8th Apr 2019, 6:08 AM
Gideon Adams
Gideon Adams - avatar