+ 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
3 Respostas
+ 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.
+ 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.