Page 95 - Programming Microcontrollers in C
P. 95

80     Chapter 2  Advanced C Topics

                              An important point of style: Recall that a few pages back a func­
                          tion strcomp() was written as an example. It did the exact same
                          operations as strcmp() above. Why should we choose one over
                          the other? Well, library functions have been written, rewritten, de­
                          bugged, and worked over for years. They work correctly, and you
                          can count on their robust construction. As a general rule, use a li­
                          brary function if you can find one to do the job that you are attempting.
                          Most of the time, programmers who write duplicates of library func­
                          tions do it to satisfy their own egos. The reward is poor when a bug is
                          discovered, especially in production code, that could have been
                          avoided by using a standard library function.

            Multidimensional Arrays


                              C supports multidimensional arrays. Programmers often find that
                          much of the need for multidimensional arrays will go away with the
                          availability of pointers. Multidimensional arrays in C are thought of
                          as arrays of arrays. This idea can be extended to more than two di­
                          mensions. A two-dimensional array is identified as

                   array[x][y]; /* [row][column] */
                          The first argument to the right can be thought of as the row dimen­
                          sion, and the second the column dimension. Elements specified by
                          the rightmost argument are stored in adjacent memory locations.
                              An array can be initialized at declaration time. For example:

                   int array [3][4] = { {10,11,12,13},
                                              {14,15,16,17},
                                              {18,19,20,21} };
                          It is equally valid to initialize the array as follows:

                   int array [3][4]={10,11,12,13,14,15,16,17,18,19,20,21};
                          Either form of initialization will place the proper numbers in the
                          proper location in memory, and the two-dimensional indices will
                          work properly in either case.
                              Frequently, it is needed to know the size of a variable in C. This
                          variable can be a basic type, an array, a multiple dimensional array, or
                          even a structure that will be introduced later. C provides an operator
   90   91   92   93   94   95   96   97   98   99   100