Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int main()
- {
- //we use pointers to save memory.
- int x = 25; //base integer
- int *p = x;
- cout << p << endl;
- //this will output the memory address of p. it's an unnamed memory location
- int y = 25; //base integer
- int *q = &y; //using the address of operator
- cout << q << endl;
- //this will output the memory address of y
- //cout << *p << endl; //this won't work. it will crash
- cout << *q << endl; //dereferencing q. This will print the value stored at the memory location q is pointing to
- x = x + 5;
- cout << x << endl;
- //x = *p + 5;
- //cout << x << endl; //crashes.
- y = *q + 5; //25 + 5
- cout << y <<endl;
- *q = *q + 5; //30 + 5
- cout << *q << endl;
- cout << y <<endl; //both will display 35. We used the pointer to change the value at the memory location (y)
- cout << &*q << endl; //& and * cancel out each other. same as writing q.
- }
Advertisement
Add Comment
Please, Sign In to add comment