Pointers are variables that contain the memory address for
another variable. A pointer is defined like a normal variable,
but with an asterisk before the variable name. The type-specifier
determines what kind of variable the pointer points to but does
not affect the actual pointer.
The address operator causes the memory address for a variable
to be returned. It is written with an ampersand sign before the
When using a pointer, referencing just the pointer such as:
Causes my_pointer to contain the address of barny. Now the
pointer can be use indirection to reference the variable it
points to. Indirection is done by prefixing an asterisk to the
This causes the value of barny to be 3. Note that the value of
my_pointer is unchanged.
Pointers offer an additional method for addressing an array.
The following array:
Can be addressed normally such as:
The same can be accomplished with:
my_array is a pointer constant.
Its value cannot be modified such as:
my_array++; This is illegal.
However, if a pointer variable is created such as:
Then modifying the pointer will correctly increment the pointer
so as to point to the next element in the array.
This will cause the value of
be 3. On a system where an
int takes up two
bytes, adding 1 to
some_pointer did not
actually increase it by 1, but by 2 so that it pointed to the
next element in the array.
Functions can also be represented with a pointer. A function
pointer is defined in the same way as a function prototype, but
the function name is replaced by the pointer name prefixed with
an asterisk and encapsulated with parenthesis. Such as:
int (*fptr)(int, char);
To call this function:
This is equivalent to:
A structure or union can have a pointer to represent it. Such
struct some_structure homer;
This defines homer_pointer to point to the structure homer. Now,
when you use the pointer to reference something in the
structure, the record selector now becomes
struct some_structure *homer_pointer;
instead of a period.
This is the same as:
The void pointer can represent an unknown pointer type.
This is a pointer to an undetermined type.