+ 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 !?

4th Jul 2018, 7:26 PM
Mohammad Alshareef
Mohammad Alshareef - avatar
6 Antworten
+ 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).
4th Jul 2018, 7:57 PM
Shadow
Shadow - avatar
0
Naitomea Am i stupid or this hard !?
6th Jul 2018, 9:30 AM
Mohammad Alshareef
Mohammad Alshareef - avatar
0
Naitomea And *p is pointer so why the value of var stored in ?
6th Jul 2018, 9:34 AM
Mohammad Alshareef
Mohammad Alshareef - avatar
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.
6th Jul 2018, 12:59 PM
Shadow
Shadow - avatar
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.
6th Jul 2018, 1:03 PM
Shadow
Shadow - avatar
0
Thank you ... i will search more
6th Jul 2018, 1:07 PM
Mohammad Alshareef
Mohammad Alshareef - avatar