+ 2
Can anyone make me understand pointers in c++. I m very new to this language
3 Respuestas
+ 6
/*sorry long post : part 1*/
If you want to understand pointers, you need to understand the memory of your computer system.
All variables you create in your program will be stored in the RAM of your system. You can consider that in this memory, there is a lot of box with a name written on it : the variable name, and inside, there is value. Of course there is no box in your computer it's just an example.
so when you write : int var=0;
c++ will take a box that can store a int and will write on it this is box "var" and will put inside the value 0.
when you say var=1; c++ will check if he has a box called "var" if he finds it, he will replace the 0 inaide by a one. (and the 0 will be lost).
Now you have to know that your box in your computer (no really there is no box), are not in the disorder. Each box have a value which its adress for example box number 7359186 is the box called "var" of type int and inside there is a 1.
You can now the adress of your variable using the & operator like this :
std::cout << &var; will output the adress of the variable var.
Of course there is a way to store this value : using pointers (here we go !).
+ 5
/* part 2 */
You have to say of which type is the variable you want to now the adress and then you can do this :
int *pointer = &var;
here we create a new box in our memory system : box called pointer of type "pointer of int" and that stored a int adress.
Be aware the name of the variable is just pointer and not *pointer, the asterisk ia just here to say you are going to create a pointer.
Also don't forget that your pointer is still only a variable ... that stored the adress od an other variable... but you can write this : cout << &pointer;
and you can create a pointer to a pointer like this :
int **pointer_of_a_pointer = &pointer;
etc...
then you have your pointer variable.
You can use the operator * on it to access the variable which the adress is stored inside the pointer box like this : *pointer = 2; here you say to c++ look inside the box called pointer, you will found a variable adress, open the box with this adress and set a 2 inside.
that how work pointers.
Still a lot to say about them, for example new, delete, smart pointers and references.
I hope it help you :-)
+ 1
A pointer is a variable containing the address of another variable, or to make things easier, you can say that it is a variable containing another variable.
int i = 5; // a simple int variable with a value of 5
int *p; // the pointer p 'points' to an int variable
p = &i; // p contains now the adress of i; &i is used to get the adress of i
cout << p; // it will print the address of the i variable
cout << *p; // it will print the value contained in the address of i (the value of i)