Page 92 - Programming Microcontrollers in C
P. 92

Pointers     77

                          written to the screen when the program is executed. A command line
                          can be read by the program. The definition of the program name main
                          when extended to read in a command line is as follows

                   void main ( int argc, char *argv[])

                          The integer variable argc is the number of entries on the command line.
                          The array of pointers to the type char argv[] contains pointers to
                          strings. When entering arguments onto the command line, they must be
                          separated by spaces. The first string pointed to by argv[0] is the name
                          of the program from the command line. The successive pointer values
                          point to additional character strings. These strings are each 0 terminated,
                          and they point to the successive entries on the command line. The value of
                          argc is the total number of command line entries including the program
                          name. It must be remembered that each entry in argv[] is a pointer to a
                          string. Therefore, if a number is entered on the command line, it must be
                          converted from a string to an integer, or floating point number, prior to its
                          use in the program. Let us see how this concept can be used. Earlier, we
                          wrote a function to calculate a Fibonacci number. Let’s use this function in
                          a program in which the argument for the Fibonacci calculation is read in
                          from the command line:

                   #include <stdio.h>
                   #include <stdlib.h>


                   long fib( int ); /* Fibonacci number function
                                         prototype */

                   int main( int argc, char* argv[] )
                   {
                       int i;
                       i = atoi(argv[1]);
                       printf(“The Fibonacci number of %d  = %ld\n”, i,
                          fib(i));
                       return 0;
                   }
                              We will not repeat the code for fib(i). A new header file,
                          stdlib.h, is included with this program. The function prototype
                          for atoi() is contained within this header file. The standard com­
                          mand line arguments are used in the call to main(). The line
   87   88   89   90   91   92   93   94   95   96   97