Page 102 - 6437
P. 102

ptr++

                          After the above operation, the ptr will point to the location 1004 because each time ptr is
                   incremented, it will point to the next integer location which is 4 bytes next to the current location.
                   This operation will move the pointer to the next memory location without impacting  the actual
                   value  at the  memory location.  If ptr points to a character whose address is 1000, then the above
                   operation will point to the location 1001 because the next character will be available at 1001.

                          Incrementing a Pointer
                          We prefer using a pointer in our program instead of an array because the variable pointer
                   can be incremented, unlike the array name which cannot be incremented because it is a constant
                   pointer. The following program increments the variable pointer to access each succeeding element
                   of the array:



                 #include <stdio.h>


                 const int MAX = 3;


                 int main ()
                 {

                    int  var[] = {10, 100, 200};
                    int  i, *ptr;


                    /* let us have array address in pointer */

                    ptr = var;
                    for ( i = 0; i < MAX; i++)
                    {


                        printf("Address of var[%d] = %x\n", i, ptr );
                        printf("Value of var[%d] = %d\n", i, *ptr );


                        /* move to the next location */

                        ptr++;
                    }
                    return 0;

                 }







                                                                                                      10
                                                                                                      5
   97   98   99   100   101   102   103   104   105   106   107