Pointers

Could someone explain how this code works.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>
using namespace std;

int main ()
{
  int firstvalue = 5, secondvalue = 15;
  int * p1, * p2;

  p1 = &firstvalue;  // p1 = address of firstvalue
  p2 = &secondvalue; // p2 = address of secondvalue
  *p1 = 10;          // value pointed to by p1 = 10
  *p2 = *p1;         // value pointed to by p2 = value pointed to by p1
  p1 = p2;           // p1 = p2 (value of pointer is copied)
  *p1 = 20;          // value pointed to by p1 = 20

  cout << "firstvalue is " << firstvalue << '\n';
  cout << "secondvalue is " << secondvalue << '\n';
  return 0;
}
Seems to be explained quite well already. What in particular do you misunderstand?
I just don't understand pointers in general,
I don't understand how secondvalue becomes 20

It relies on you knowing that memory is where information is stored, and that we use a number to label each piece of memory. For example, piece of memory number 73 is right next to piece of memory number 74 and piece of memory number 75.

If you understand that, you can understand this: http://www.cplusplus.com/articles/EN3hAqkS/
Last edited on
I am going to translate what you have slightly, assuming you know arrays already.

int ram[] = {0,0,5,0,15,10,100}; //a variable that represents the memory of your computer conceptually. It has in it first and second value, as most variables (lets skip the exceptions for today) live in ram. This isnt your computer's ram, of course, its just an array to explain the concept. Firstvalue is at 2 and secondvalue is at 4, conceptually, for this example.

int p1 = 2; // represents p1 = &firstvalue
ram[p1] = 10; //this is what *p1 = 10 above does.
now ram looks like this:
ram[] = {0,0,10,0,15,10,100};
int p2 = 4; //p2 = &second
ram[p2] = ram[p1]; //this is what *p2=*p1 does.
now ram looks like this:
ram[] = {0,0,10,0,10,10,100};
p1 = p2; //p1 becomes 4.
ram[p1] = 20; //*p1 = 20;
now ram looks like this:
ram[] = {0,0,10,0,20,10,100};

so as you can see, you can think of pointers as integer index into that great big array in the sky that we think of as your computer's ram. Changing the index does not change the value, and changing the value does not change the index, they are distinct things, and you have to keep track of both correctly.

There are more details behind all this, but if you think of it this way, you will understand the code block and the high level concept of pointers.
Last edited on
Thanks for explaining it, I understand it now.
Topic archived. No new replies allowed.