Variables are stored at specific locations in memory. A pointer is a special type of variable that instead of containing data, points to a location in memory where data is stored. The pointer contains the address where another variable (generally) is stored in memory.
The * character is used to denote a pointer. The following shows the declaration of an integer and a pointer to an integer:
int a; //a regular integer int *p; //a pointer to an integerThe address of a variable can be determined by preceding the variable name with an & symbol. The value contained at an address that a pointer points to can be determined by preceding the name of the pointer with a * symbol. The following example should make this clear.
#include <stdio.h>
int main()
{
int a; //an integer variable
int *p; //a pointer to an integer
//assign a value to a
a = 6;
//make p point to the location of a
p = &a; //this reads "p = the address of a"
//Display the value of a and the value of the location p points to
//Notice that we use the *p to indicate the value p points at
printf("The value of a is %d and the value p points at is %d\n", a, *p);
//Since p points at the location where a is stored, if we change
//the value p points at, we will also change a
*p = 17;
printf("The value of a is %d and the value p points at is %d\n", a, *p);
return 0;
}
A pointer that does not point to anything should be set to NULL. For example:
int *p;
p = NULL;
NULL is used to indicate unassigned pointers.