Page 89 - Programming Microcontrollers in C
P. 89
74 Chapter 2 Advanced C Topics
C is completely unforgiving if you exceed the boundaries of the
array in your calculations. C does not have intrinsic boundary checks,
and it is possible to increment pointers right off the end of an array.
For that matter, the array index can be decremented to addresses
below the beginning of the array. When a program makes such a
mistake, it will destroy other data, perhaps destroy the program be
ing executed, or in the worse case, the program can crash the system.
The simple single-tasking computers that run MS-DOS or similar
operating systems have no memory protection feature that protects
one task from another. In such cases, a program that runs wild and
overwrites memory not assigned to it can destroy other tasks that are
loaded in memory whether they are running or not.
EXERCISES
1. Write several versions of a function that copies one string into
another.
2. Write a function that concatenates two strings. Concatenation of
two strings means that one string will be written at the end of the
other. Write this function with and without the use of pointers.
What is the advantage of the pointer version of the function?
Let us consider a problem that will be analyzed in more detail
later. Suppose that a function is needed that will sort the contents of
an array into ascending (or descending) order. There are several sort
functions, and each has its own set of advantages and disadvantages.
The simplest and probably most intuitive is called the bubble sort. In
a bubble sort, a swap flag is reset. The first entry in the array is
compared with the second, and if they are in the wrong order, they
are swapped. Then the second entry is compared with the third, and
they are swapped or not. If a swap ever occurs, the swap flag is set.
The elements of the array are successively compared and swapped
until all of the elements in the array have been compared. If a swap
has occurred during the scan of the array, the swap flag is reset, and
the whole process is repeated. This process repeats until the scan of
the array causes no swaps to occur. At that time, the array is in order.
If the array contains n elements, this approach requires on the
order of n squared compares and swaps. For large arrays, the time to
sort an array with a bubble sort is inordinate. Another approach was