Pointers to Simple Variables

Summary: A pointer variable contains the address of a data object.

Although pointers have many different uses, it takes only a few words to say what a pointer is. A “pointer” is a variable that contains the address of some other data object—usually a variable. Because a pointer contains the other variable's address, it is said to “point to” that variable.

This section uses the program POINTER.C to demonstrate the basic mechanics of pointers—how to declare and initialize a pointer and use it to access a simple variable:

/* POINTER.C: Demonstrate pointer basics. */

#include <stdio.h>

main()

{

int val = 25;

int *ptr;

ptr = &val;

printf( " val = %d\n", val );

printf( "*ptr = %d\n\n", *ptr );

printf( "&val = %u\n", &val );

printf( " ptr = %d\n", ptr );

}

Here is the output from POINTER.C:

val = 25

*ptr = 25

&val = 5308

ptr = 5308

(The third and fourth output lines show addresses. These may differ when you run POINTER.C depending on factors such as available memory.)

POINTER.C creates a pointer variable named ptr and makes ptr point to an int variable named val. Then it prints the two values to show that ptr can access the value stored in val. The program goes on to print the address where val is stored and the address contained in ptr, to show they are the same.