Page 93 - Programming Microcontrollers in C
P. 93

78     Chapter 2  Advanced C Topics

                   i = atoi(argv[1]);

                          causes the function atoi—ASCII to integer conversion—to be ex­
                          ecuted with a pointer as an argument. This pointer points to the first
                          argument following the program name on the command line. In this
                          case, it will be pointing to an ASCII string that contains the number
                          to be used as an argument for the fib() call. This string must be
                          converted to an integer before fib() can operate on it, which is
                          exactly what the atoi() function accomplishes. The final line in
                          this program prints out the result of the calculation.
                              Another example of use of the command line arguments is to print
                          out the command line. The following program will accomplish this task.
                   #include <stdio.h>
                   int main( int argc, char* argv[] )
                   {
                       int i;
                       for(i=0; argc--; i++)
                       printf(“%s “,argv[i]);
                       printf(“\n”);
                       return 0;
                   }
                              The arguments to main() are the same as before. This program
                          enters a for loop that initializes i to zero. It decrements argc each
                          time it tests its value, and executes until the loop in which argc is
                          decremented to 0. The printf call

                   printf(“%s “,argv[i]);

                          prints out the string to which argv[i] points. Notice the space in the
                          string “%s “. This space will force a space between each argument as
                          it is printed. The program is written so that there are no new line charac­
                          ters printed. Arguments will all be on one line, and they will each be
                          separated by a space. The printf() statement after execution of the
                          for() loop will print out a single new line so that the cursor will return
                          to the next line after the program is executed.
                              Command line entry is but a simple example of use of arrays of
                          pointers. Another area in which arrays to pointers are needed is in order­
                          ing strings of data. For example, it is possible to collect a large number
                          of words in memory, say from an input stream. Suppose that it is needed
                          to alphabetize these words. We saw earlier, that the shell sort will order
   88   89   90   91   92   93   94   95   96   97   98