Page 84 - Programming Microcontrollers in C
P. 84
Pointers 69
• Pointers can be subtracted. Two pointers to like types in the same
array can be subtracted with a C arithmetic expression. The result
of the subtraction will be the number of elements between the two
pointers, not the difference in the values of the pointers.
• Pointers can be incremented and decremented. A pointer into an
array can be either incremented or decremented. The result will be
a pointer that points to an adjacent element in the array.
• Pointers can be assigned. A pointer can be assigned to another
pointer of the same type.
Pointers cannot be added, multiplied, divided, masked, shifted,
or assigned a pointer value of an unlike type. Pointers can be as
signed to another pointer of the type void*.
The name of an array is a pointer to the first element in this array.
This type of variable occupies a special place in C. The name can
always be used as a pointer, and assigned to another pointer, but it
cannot be assigned to. Any attempt to assign a new value to the array
name would upset the beginning of the array to the program.
Therefore, an array name as a pointer can be used as a value on
the right side of an assignment equal sign, but it cannot be used on
the left side of the equal sign. C variables are broken into the types
rvalue and lvalue. All C variables, with the exception of the
names of functions and arrays, are both rvalues and lvalues.
They can be used on either side of an equal sign in an assignment
statement. Function names and array names are rvalues and can
be used only on the right side of the equal sign in an assignment
statement. Variables declared as constants and constants created by
the #define statement are also rvalues.
The type void* has a special meaning when applied to pointers.
A void pointer (sometimes referred to as a generic pointer) is a pointer
that does not point at any specific type. Some functions will return
void pointers, and to use these pointers, they must be cast onto the
type that they represent. Therefore, a pointer of the type void* can
be assigned the value of a typed pointer. However, unless the void*
pointer is cast onto the specified type, the increment, decrement,
subtraction, and so forth will not work. A void pointer can be
used in expressions, but it is impossible to alter its value.