Page 81 - Programming Microcontrollers in C
P. 81

66     Chapter 2  Advanced C Topics

                       x = *px;

                              Here the asterisk (*) is a unary operator that applies to a pointer
                          and directs the compiler to use the integer pointed to by the pointer
                          px in the assignment. The unary * is referred to as the dereference
                          operator. With these two operators, it is possible to move from vari­
                          able to pointer and back again with ease.
                              A pointer is identified as a pointer to a specific type by state­
                          ments like

                   int *px,*pa;
                   long *pz;
                   float *pm;

                              In the above declarations, each of the variables preceded by the
                          unary asterisk identifies a pointer to the declared type. The pointers
                          px and pa are the addresses of integers. pz is the address of a long,
                          and pm is the address of a floating point number. Always remember:
                          if pk is a pointer to an integer, *pk is an integer. Therefore, the
                          declarations in the above examples are correct and do define ints,
                          longs and floats. However, when the compiler encounters the
                          statement
                   int *pi;

                          it provides memory space for a pointer to the type int, but it does
                          not provide any memory for the int itself. Suppose that a program
                          has the following declaration:

                   int m,n;
                   int *pm;
                              The statement

                   m = 10;
                   pm = &m;
                          will assign the value 10 to m and put its address into the pointer pm.
                          If we then make the assignment
                   n = *pm;

                          the variable n will have a value 10.
                              Another interesting fact about pointers is shown in the following
                          example:
   76   77   78   79   80   81   82   83   84   85   86