-6

I am kinda new to c++ and I don't get why should I use pointers and references?

for example Idon't get how this works

int a = 8;
int *p1;
p1 = &a;
  • 2
    What don't you get? This is very basic and has been discussed in many places including your textbook/reference manual. – NathanOliver Nov 11 '15 at 15:01
  • @NathanOliver is correct, this has been discussed many times. I'd suggest a quick google search and reading docs like [this](http://www.cplusplus.com/doc/tutorial/pointers/) – Daniel Robertson Nov 11 '15 at 15:03
  • Do you really mean, "I don't get why this works" or are you saying, "I don't see the value of this"? – Kanga_Roo Nov 11 '15 at 15:07
  • Possible duplicate of [How do function pointers in C work?](http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – Richard Nov 11 '15 at 16:15

1 Answers1

0

A pointer is an address of a variable.

Imagine ram as consecutive boxes. Each box has an address.

Now in your example.

int a = 8; //declares a variable of type int and initializes it with value 8

int *p1; //p1 is a pointer meaning that the variable p1 holds an address instead of a value.

p1 = &a; //The operator &is called address of. This statement makes p1 point to the address of a. That is p1 holds the address of a.

In order to access the value of a instead of the address you need to deference it.

*p1 = 9; //now a = 9
KostasRim
  • 2,053
  • 1
  • 16
  • 32
  • 1
    A pointer isn't always the address of a variable, it could be a pointer to an element in an array, pointer to a volatile memory location etc. – TartanLlama Nov 11 '15 at 15:16
  • @TartanLlama an element of an array has an address, by assigning that address to a pointer is nothing more than the address of that element. Well in an extend we call it a pointer to an array element, but it is still an address. Yes you can have pointers to pointers etc, i just wanted to make an example that is very simple. – KostasRim Nov 11 '15 at 15:23