Page 91 - Programming Microcontrollers in C
P. 91
76 Chapter 2 Advanced C Topics
The corresponding elements in each subarray are compared, and
if they are out of order, they are swapped. At the close of this opera
tion, a new set of subarrays are created, and the process is repeated
over these subarrays. Eventually, the gap between elements in the
subarrays will be reduced to one, and the array contents will be sorted.
The outer for loop above controls the splitting of the arrays into
the subarrays. The second loop steps along the array pairs. The in
nermost loop successively compares the elements that are separated
by gaps in the subarrays. If elements are found that are out of order,
they are reversed or swapped in the array.
EXERCISES
1. Restate the shell sort above to use arrays rather than pointers to
arrays.
2. Write a program that reads in characters from the input stream and
record the number of occurrences of each character. Calculate the
percentage occurrence of each character, and print out the result in
ascending order of percentage of occurrence.
Functions can return pointers. For example, prototype to a func
tion that returns a pointer is:
int *able(char* );
Here able returns a pointer to an integer.
In C, a NULL pointer is never used. A NULL pointer implies that
something is to be stored at the address zero. This address is never avail
able for data storage, so no function can return a valid NULL pointer.
The NULL pointer can be used as a flag or an error return. The pro
grammer should never allow a NULL pointer to be dereferenced, which
implies that data are read or stored at 0.
If C will support a pointer to a variable, it requires but little imagi
nation to reason that C will support pointers to pointers. In fact, there
is no practical limit in the language to the depth of dereference C
will support. C will also allow arrays of pointers, and pointers to
functions. (We discussed pointers to arrays in the preceding section.)
An array of pointers can be very useful when needed. A most obvi
ous use for an array of pointers is to read the contents of a command
line to a program. So far in our discussion of programs, there have
been no provisions for reading the content of a command line that is