A pointer is a variable that contains an address in memory where
the value referenced by the pointer is stored. In other words, a pointer
is a variable that points to another variable by referring to the
other variable’s address. Pointers contain memory addresses,
not values. Pointer variables must be declared in C using the * notation. Pointers are widely used to reference data
stored in structures and to pass data among functions (by passing
the addresses of the data).
For example,
int *ip;
declares a pointer named ip that points
to an integer variable.
Now suppose you want to assign an address to pointer ip. To do this, you can use the & notation. For example,
ip = &a;
assigns the address of variable a to
pointer ip.
You can retrieve the value of variable a that pointer ip is pointing to by
*ip
Alternatively, you can set the value of the variable that pointer
ip points. For example,
*ip = 4;
assigns a value of 4 to the variable
that pointer ip is pointing. The use of pointers
is demonstrated by the following:
int a = 1;
int *ip;
ip = &a; /* &a returns the address of variable a */
printf("content of address pointed to by ip = %d\n", *ip);
*ip = 4; /* a = 4 */
printf("now a = %d\n", a);
Here, an integer variable a is initialized
to 1. Next, ip is
declared as a pointer to an integer variable. The address of variable a is then assigned to pointer ip. Next, the integer value of the address pointed to by ip is printed using *ip. (This
value is 1.) The value of variable a is then indirectly set to 4 using *ip. The new value of a is then printed. Pointers can also point to the beginning
of an array, and are strongly connected to arrays in C.