My current understandings of Pointers

Pointers tells the system to go somewhere else to find what it’s looking for

How are pointers really used?

  • They can be used to refer to new memory reserved during program execution.
  • They can be used to refer and share large data structures without making a copy of the structures.
  • Or used to specify relationships among data – linked lists, trees, graphs etc.

In this example code I undestand why secondvalue ended up being 20, but not why firstvalue ended being 10.

// more pointers
#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;
}

*I’m thinking that if p1 = p2; and then p1 = 20; that the value of both will be 20. So it’s a bit confusing for me there.

1 Like

p1 = p2 would mean you are setting the address of p1 to p2. So both p1 and p2 both point to secondvalue.

Sounds like you are thinking about your outputting being this. Which would result in it printing 20 twice.

cout << "p1 = " << *p1 << "\n";
cout  << "p2 = " << *p2 << endl;
1 Like

Thanks for the explanation! That was exactly what I was thinking. I feel more comfortable now with pointers.

Privacy & Terms