+ 1
What is going on ?
#include <iostream> using namespace std; int main() { int var = 50; int *p; p = &var; cout << var << endl; // Outputs 50 (the value of var) cout << p << endl; // Outputs 0x29fee8 (var's memory location) cout << *p << endl; /* Outputs 50 (the value of the variable stored in the pointer p) */ return 0; } The question is : WHO TELL THE COMPUTER THAT *p = 50 !?
6 odpowiedzi
+ 4
You (indirectly) when saying "p = &var".
Whenever you declare a variable, the computer reserves some space of memory to store the information. That space has a unique adress, the variable name is only an identifier for that adress, so you don't have to write some cryptic string every time you want to access the variable.
Now you let p point to var, assigning it the memory address of p. The (*) does the opposite of what & does (returning an address).
So "*p" returns what is stored in that memory address, in your case 50 (therefore it is called "dereference operator).
0
Naitomea
Am i stupid or this hard !?
0
Naitomea
And *p is pointer so why the value of var stored in ?
0
Pointers can be a very abstract concept when you encounter them for the first, so you shouldn't feel stupid if you don't immediately master them (I can tell!). And as I said, the value of var is not directly stored in p.
For example, imagine a jar. The jar is titled "1", and is filled with marmelade.
The jar represents a memory block, its title is its unique address, and the marmelade is the data we store in it.
A pointer is exactly like this, but the inside is not filled with yummy marmelade, but with the title of another jar. But because we know the title of said jar, we can identify it, walk over to it and see what is inside (yummy marmelade). That is called dereferencing a pointer by using the asterisk (*).
Not sure if this helps, I just made it up.
0
If Sololearn's tutorial is not clear enough, there are plenty of other explanations on the internet:
https://gist.github.com/ericandrewlewis/720c374c29bbafadedc9
http://www.cplusplus.com/doc/tutorial/pointers/
https://www.programiz.com/cpp-programming/pointers
Also, you are not the only one having trouble understanding them, so you can also search for "pointer" in this Q&A section.
0
Thank you ... i will search more