Chapter 5. Pointers

sorting the programmers from the students

5.1. The Basics

A limitation you may have noticed is that functions can only affect your program via their return value, so what do you do when you want a function to alter more than one variable? You use pointers. A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier. There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators. When you place an ampersand in front of a variable you will get it's address, this can be store in a pointer. When you place an asterisk in front of a pointer you will get the value at the memory address pointed to. As usual, we'll look at a quick code example to show how simple this is.

Example 5-1. pointers_are_simple.c

#include <stdio.h>

int
main()
{
  int my_variable = 6, other_variable = 10;
  int *my_pointer;

  printf("the address of my_variable is    : %p\n", &my_variable);
  printf("the address of other_variable is : %p\n", &other_variable);

  my_pointer = &my_variable;

  printf("\nafter \"my_pointer = &my_variable\":\n");
  printf("\tthe value of my_pointer is %p\n", my_pointer);
  printf("\tthe value at that address is %d\n", *my_pointer);

  my_pointer = &other_variable;

  printf("\nafter \"my_pointer = &other_variable\":\n");
  printf("\tthe value of my_pointer is %p\n", my_pointer);
  printf("\tthe value at that address is %d\n", *my_pointer);

  return 0;
}
      
The output shows you the address of the two variables, the addresses your system assigns to the variables will be different to mine. In printf() you'll notice we used %p to display the addresses. This is the conversion specifier for all pointers. Anyway, here's the output I got:
the address of my_variable is    : 0xbffffa18
the address of other_variable is : 0xbffffa14

after "my_pointer = &my_variable":
        the value of my_pointer is 0xbffffa18
        the value at that address is 6

after "my_pointer = &other_variable":
        the value of my_pointer is 0xbffffa14
        the value at that address is 10
     
There. That's not too complicated. Once you are comfortable with pointers you're well on your way to mastering C.