Page 67 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 67

Fundamentals of Data Structures




                    Notes
                                                        Figure 5.1: Pointer, Variables and Memory



























                                   Source:  http://www.cs.cf.ac.uk/Dave/C/node10.html
                                   Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip is declared
                                   to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the
                                   value 100.
                                   Next y gets assigned to the contents of ip. In this example ip currently points to memory location
                                   100 — the location of x. So y gets assigned to the values of x — which is 1. We have already seen
                                   that C is not too fussy about assigning values of different type. Thus it is perfectly legal (although
                                   not all that common) to assign the current value of ip to x. The value of ip at this instant is 100.
                                   Finally we can assign a value to the contents of a pointer (*ip).
                                   When a pointer is declared it does not point anywhere. You must set it to point somewhere
                                   before you use it.
                                   So ...
                                    int *ip;
                                          *ip = 100;
                                   will generate an error (program crash!!).
                                   The correct use is:
                                    int *ip;
                                                  int x;
                                                  ip = &x;
                                                  *ip = 100;
                                   We can do integer arithmetic on a pointer:
                                    float *flp, *flq;
                                                  *flp = *flp + 10;
                                                  ++*flp;
                                                  (*flp)++;
                                                  flq = flp;




          60                                LOVELY PROFESSIONAL UNIVERSITY
   62   63   64   65   66   67   68   69   70   71   72