Page 171 - DCAP507_SYSTEM_SOFTWARE
P. 171

Unit 10: Programming Languages Concept (I)




          We  can also assign pointer values to other pointer variables. If we declare a second pointer  Notes
          variable:
                int *ip2;

          then we can say
                ip2 = ip;
          Now ip2 points where ip does;
          Now, if we set ip to point back to i again:

                ip = &i;
          We can now see that the two assignments
                ip2 = ip;
          and

                *ip2 = *ip;
          do two very different things. The first would make ip2 again point to where ip points (in other
          words, back to i again). The second would store, at the location pointed to by ip2, a copy of the
          value pointed to by ip; in other words (if ip and ip2 still point to i and j respectively) it would set
          j to i's value, or 7.

          It's important to keep very clear in your mind the distinction between a pointer and what it
          points to. The two are like apples and oranges (or perhaps oil and water); you can't mix them.
          You can't ``set ip to 5'' by writing something like
                 ip = 5;               /* WRONG */
          5 is an integer, but ip is a pointer. You probably wanted to ``set the value pointed to by ip to 5,''
          which you express by writing
                 *ip = 5;
          Similarly, you can't ``see what ip is'' by writing
                 printf("%d\n", ip);   /* WRONG */

          Again, ip is a pointer-to-int, but %d expects an int. To print what ip points to, use
                 printf("%d\n", *ip);
          Finally, a few more notes about pointer declarations. The * in a pointer declaration is related to,
          but different from, the contents-of operator *. After we declare a pointer variable
                 int *ip;
          the expression
                 ip = &i

          sets what ip points to (that is, which location it points to), while the expression
                 *ip = 5
          sets the value of the location pointed to by ip. On the other hand, if we declare a pointer variable
          and include an initializer:
                 int *ip3 = &i;






                                           LOVELY PROFESSIONAL UNIVERSITY                                   165
   166   167   168   169   170   171   172   173   174   175   176