Page 70 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 70

Unit 5: Pointers




          Consider the following:                                                               Notes
           int a[10], x;
                          int *pa;

                          pa = &a[0]; /* pa pointer to address of a[0] */


                          x = *pa;
                          /* x = contents of pa (a[0] in this case) */

                                    Figure 5.3: Arrays and Pointers


                            0        1        ………….                      9
                         a

                            pa   ++pa               pa  +  1


          Source:  http://www.cs.cf.ac.uk/Dave/C/node10.html
          To get somewhere in the array (Figure 5.3) using a pointer we could do:
           pa + i  ≡  a[i]
          There is no bound checking of arrays and pointers so you can easily go beyond array memory
          and overwrite other things.
          C however is much more subtle in its link between arrays and pointers.
          For example we can just type
           pa = a;

          instead of
           pa = &a[0]

          and
           a[i] can be written as *(a + i).
          i.e.   &a[i]  a + i.
          We also express pointer addressing like this:
           pa[i]  *(pa + i).
          However pointers and arrays are different:

          A pointer is a variable. We can do pa = a and pa++.
          An Array is not a variable. a = pa and a++ ARE ILLEGAL.
          We can now understand how arrays are passed to functions. When an array is passed to a
          function what is actually passed is its initial elements location in memory. So:
           strlen(s)  ≡  strlen(&s[0])
          This is why we declare the function:
           int strlen(char s[]);





                                           LOVELY PROFESSIONAL UNIVERSITY                                   63
   65   66   67   68   69   70   71   72   73   74   75