+ 2

Help please!

So, I have been learning C++ and I'm stuck at pass by reference with pointers it isn't that much confusing but I want to understand this (let's just skip the #include and these thing) void myFunc(int *x){ *x = 100; } int main(){ int var = 20; myFunc(&var); cout << var; return 0; } so like *x is a pointer which points to 100 which kind of doesn't amke sense and &var is tge address of var not value so what's happening here.

21st Jan 2018, 1:19 PM
Lewinsky
Lewinsky - avatar
2 Answers
+ 2
Every variable is stored in a memory address. When you set a variable, it is changing the value that is stored in that memory address. A pointer is a variable that holds a memory address, so when you change the value stored in the memory address held by that pointer, that new value is the value of any variable connected to that address. var means the value stored in var’s address, &var means the address itself. For pointers, *x means the value in the address it points to, x means the address itself, and &x means x’s address because just like any other variable, it’s value, which is the address of another variable, gets stored in an address. When you call myFunc(&var), it makes it so x = &var. This means that changing the value stored in the address x points to changes the value of var because x points to var’s address. I know pointers are confusing, but you’ll get it eventually.
21st Jan 2018, 2:13 PM
Jacob Pembleton
Jacob Pembleton - avatar
0
thanks to both of you ;)
21st Jan 2018, 2:15 PM
Lewinsky
Lewinsky - avatar