Pointer

From LQWiki
Jump to navigation Jump to search

A pointer is reference to an object in memory. The pointer contains the memory address of the object that it references. Pointers are useful in many data structures, such as linked lists.

A C++ example:

#include <iostream>

using namespace std;

int main()
{
   int v = 5;     // Declare integer variable, initialize to 5
   int *p;        // Declare pointer to an integer

   p = &v;        // p is assigned the memory address of v (p now "points" to v)

   cout << p << endl;    // Print the value of p (in this case, the memory address of v, for example: 0012FF60)
   cout << *p << endl;   // Print the value of the object referenced by p (in this case, the value of v, 5)

   v++;	          // Increment v

   cout << *p << endl;   // This will print 6

   (*p)++;               // Increment the value that p points to

   cout << v << endl;	  // This will print 7
 
   return 0;
}