Sunday, March 17, 2013

Programming Basics #1

Pointer Tutorial

Mostly saving this off for later use, in case someone asks me how pointers work, which seems to happen pretty frequently...

Source:
1:  #include <iostream>  
2:    
3:  using namespace std;  
4:    
5:  int pause;  
6:    
7:  int main()  
8:  {  
9:        int x=1,y=2;  
10:       int *p1, *p2;     // pointers, just hold a memory address  
11:       p1=&x;            // p1 = address of x  
12:       p2=&y;            // p2 = address of y  
13:       int *pholder;     // need this to swap them later  
14:       cout << "p1 = " << p1 << endl;   
15:       cout << "p2 = " << p2 << endl;  
16:       cout << "*p1 = " << *p1 << endl;  
17:       cout << "*p2 = " << *p2 << endl << endl;  
18:       cout << "Switching..." << endl << endl;  
19:       pholder=p1;          // save p1 (which is a memory address)  
20:       p1=p2;               // p1 (addr. of x) = p2 (addr. of y)  
21:       p2=pholder;          // p2 (addr. of y) = p1 (addr. of x)  
22:       cout << "p1 = " << p1 << endl;  
23:       cout << "p2 = " << p2 << endl;  
24:       cout << "*p1 = " << *p1 << endl;  
25:       cout << "*p2 = " << *p2 << endl;  
26:    
27:       cin >> pause;  
28:       return 0;  
29:  } 

Output:
 p1 = 003FFD9C  
 p2 = 003FFD90  
 *p1 = 1  
 *p2 = 2  
   
 Switching...  
   
 p1 = 003FFD90  
 p2 = 003FFD9C  
 *p1 = 2  
 *p2 = 1  

No comments:

Post a Comment