Page 83 - Programming Microcontrollers in C
P. 83
68 Chapter 2 Advanced C Topics
Pointers work with arrays. Suppose that you have
int *pa;
int a[20];
As we have already seen,
pa = a;
assigns the address of the first entry in the array to the pointer pa
much the same as
pa = &a[0];
does. To increment the pointer to the next location in the array, you
may use
pa++;
or
pa = pa + 1;
In any case, the pointer that is 1 larger than pa points to the next
element in the array. This operation is true regardless of the type that
pa points to. If pa points at an integer, pa++ points to the next
integer. If pa points at a long, pa++ points to the next long. If
pa points to a long double, pa++ points to the next long double. In
fact, if pa points to an array of arrays, pa++ points to the next array
in the array of arrays. C automatically takes care of knowing the
number that must be added to a pointer to point to the next element
in an array.
In the above case, since a is an array of 20 integers, and pa
points to the first entry in the array, it follows that pa+1 points to
the second element in the array, and pa+2 points to the third ele
ment. Similarly, *(pa+1) is the second element in the array and
*(pa+2) is the third element.
There is a set of arithmetic that can be applied to pointers. This
arithmetic is different from the normal arithmetic that can be applied
to numbers. In all cases, the arithmetic applies to pointers of like
types pointing to within the same array only. When these conditions
are met, the following arithmetic operations can be completed:
• Pointers can be compared. Two pointers to like types in the same
array can be compared in a C logical expression.