Page 76 - DCAP407_DATA_STRUCTURE
P. 76

Unit 4: Pointers





                                  b[5] = 0;                    //b[offset of 5] = 0
                                  *(b+5) = 0;                 //pointed by (a+5) = 0
                                  These two expressions are equal and valid if b is a pointer or an array.
                                  Three points need to be remembered while using pointers with arrays. They are:
                                  1. Elements of an array are always stored in contiguous memory locations.

                                  2. Incrementing or decrementing pointer variables  lead  to incrementing or
                                  decrementing memory location, depending on the data type of the defined pointer
                                  variable.
                                  3. The first element of an array is always numbered as zero, which makes the last
                                  element one less than the size of the array.

               4.5.1   Array of Pointers
               A two-dimensional  array is  a collection of one-dimensional arrays.   In the case of two-dimensional
               arrays, a single pointer can  be used to point to  the  contiguous one-dimensional arrays.  Therefore,
               instead of defining a two–dimensional array as;
               data_type array_name[ep1][ep2]
               we can define the two–dimensional array as:
                data_type (*pt)[ep2];
               Here, data_type is the data type of the array, array_name is the name of the array, and ep1 and ep2 are
               the maximum number of elements in that row or column.
               A two-dimensional vector with 3 rows and 3 columns can be initialized as:
               int  x[3][3] = {
                              {2,4,6},
                              {3,6,9},

                              {4,8,12}
                              };
               Figure 4.1 shows the row-wise representation of elements of the matrix x:

                                       Figure 4.1: Representation of Elements in Memory



















               Pointers can be used to declare x as:
               int (*x)[3];




                                        LOVELY PROFESSIONAL UNIVERSITY                           69
   71   72   73   74   75   76   77   78   79   80   81