Hollowfires

Untitled

Mar 28th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. //we use pointers to save memory.
  8.  
  9. int x = 25; //base integer
  10. int *p = x;
  11. cout << p << endl;
  12. //this will output the memory address of p. it's an unnamed memory location
  13.  
  14.  
  15.  
  16. int y = 25; //base integer
  17. int *q = &y; //using the address of operator
  18. cout << q << endl;
  19. //this will output the memory address of y
  20.  
  21. //cout << *p << endl; //this won't work. it will crash
  22. cout << *q << endl; //dereferencing q. This will print the value stored at the memory location q is pointing to
  23.  
  24. x = x + 5;
  25. cout << x << endl;
  26. //x = *p + 5;
  27. //cout << x << endl; //crashes.
  28.  
  29.  
  30. y = *q + 5; //25 + 5
  31. cout << y <<endl;
  32.  
  33. *q = *q + 5; //30 + 5
  34. cout << *q << endl;
  35. cout << y <<endl; //both will display 35. We used the pointer to change the value at the memory location (y)
  36.  
  37. cout << &*q << endl; //& and * cancel out each other. same as writing q.
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment