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.