Page 66 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 66

Unit 5: Pointers




          5.1 Concept of Pointers                                                               Notes

          A pointer is a variable which contains the address in memory of another variable. We can have
          a pointer to any variable type. Simply stated, a pointer is an address. Instead of being a variable,
          it is a pointer to a variable stored somewhere in the address space of the program. It is always
          best to use an example, so examine the next program [POINTER.C] which has some pointers in
          it.
          The following two rules are very important when using pointers and must be thoroughly
          understood. They may be somewhat confusing to you at first but we need to state the definitions
          before we can use them. Take your time, and the whole thing will clear up very quickly.
          1.   A variable name with an ampersand (&) in front of it defines the address of the variable
               and therefore points to the variable.
          2.   A pointer with a star in front of it refers to the value of the variable pointed to by the
               pointer
          The unary or monadic operator & gives the “address of a variable”.
          The indirection or dereference operator * gives the “contents of an object pointed to by a
          pointer”.
          A pointer must be defined to point to some type of variable. Following a proper definition, it
          cannot be used to point to any other type of variable or it will result in a type incompatibility
          error. In the same manner that a float type of variable cannot be added to an int type variable, a
          pointer to a float variable cannot be used to point to an integer variable.

          To declare a pointer to a variable do:
           int *pointer;

               !
             Caution  We must associate a pointer to a particular type: You can’t assign the address of a
             short int to a long int, for instance.
          Consider the effect of the following code:
           int x = 1, y = 2;
                          int *ip;
                          ip = &x;
           y = *ip;
           x = ip;
                          *ip = 3;
          It is worth considering what is going on at the machine level in memory to fully understand how
          pointer work.




             Notes  A pointer is a variable and thus its values need to be stored somewhere. It is the
            nature of the pointers value that is new.


                 Example: Consider Figure 5.1. Assume for the sake of this discussion that variable
          x resides at memory location 100, y at 200 and ip at 1000.




                                           LOVELY PROFESSIONAL UNIVERSITY                                   59
   61   62   63   64   65   66   67   68   69   70   71