next up previous contents index
Next: Pointers and subroutines Up: Pointers Previous: Pointers   Contents   Index


What is a pointer?

The following program illustrates a simple illustration of the use of a pointer:
#include <stdio.h>
int main(void) {
  int count, *p;
  count = 22;
  p = &count;
  printf("count is %d\n", count);
  printf("p is %ld\n", p);
  printf("*p is %d\n", *p);
  return 0;
}
Here, we create an integer count, and declare an int pointer p, declared as int *p. The command p = &count uses the address operator to associate the pointer p to the variable count. The results of running this program is
count is 22
p is 1245048
*p is 22
(the second line may differ on another machine, or at a different time). The important point for now is that p is some (perhaps mysterious) integer, whereas *p (being 22, the same as count) is the value of the pointer.

In a simplified way, one can think of pointers in the following way. When one declares a variable, your program asks the system for memory to store it. This memory has two (distinct) properties - the value stored, and the location (address) of where the memory block is. Running the program on different machines, or at another time, will result in the same value being stored, but the address location of the memory block may change. In the above example, p = &count associates the pointer with the address in memory where count is stored, and *p is used to access the value of the contents of that memory.

Consider the following program:

#include <stdio.h>
int main(void) {
  int v1, v2, *p;
  v1 = 22;
  v2 = v1;
  p = &v1;
  printf("v1=%d, v2=%d, p=%d\n", v1, v2, *p);
  v1 = 33;
  printf("v1=%d, v2=%d, p=%d\n", v1, v2, *p);
  return 0;
}
The results of running it are
v1=22, v2=22, p=22
v1=33, v2=22, p=33
What may be surprising is that, after v1 is set to 33, the value of *p changes (note that the value of v2 doesn't change). This though reflects a fundamental property of pointers - changing the value of the variable stored in memory doesn't change the address of that memory.
next up previous contents index
Next: Pointers and subroutines Up: Pointers Previous: Pointers   Contents   Index