Friday, July 29, 2016

C Basics - Pointer Arithmetic in C

There are four arithmetic operators that can be used on pointers: ++, --, +, and -.
  • Incrementing a pointer increases its value by the number of bytes of its data type.
  • Decrementing a pointer decreases its value by the number of bytes of its data type.
  • Pointers may be compared by using relational operators, such as ==, <, and >.

#include <stdio.h>

int main () {

   int  data[5] = {100, 200, 300, 400,500};
   int  i, *a;

   /* initialize the pointer */
 printf("--Incrementing pointer--\n");   
   a = data;
   printf("Address of a is 0x%x\n", a );
   printf("Value of *a is %d\n", *a );
   
   a = a + 1;
   printf("Address of a=a+1 is 0x%x\n", a );
   printf("Value of *a is %d\n", *a );
   
   a++;
   printf("Address of a++ is 0x%x\n", a );
   printf("Value of *a is %d\n", *a );

 printf("--Decrementing pointer--\n");
   a = &data[4];
   printf("Address of a is 0x%x\n", a );
   printf("Value of *a is %d\n", *a );
   
   a = a - 1;
   printf("Address of a=a-1 is 0x%x\n", a );
   printf("Value of *a is %d\n", *a );
   
   a--;
   printf("Address of a-- is 0x%x\n", a );
   printf("Value of *a is %d\n", *a );
   
 
    printf("--Comparing pointer--\n");
   a = data;
   i = 0;
 
   while ( a <= &data[4] ) {

      printf("Address of data[%d] = 0x%x\n", i, a );
      printf("Value of data[%d] = %d\n", i, *a );
      
      a++;
      i++;
   }
 
   return 0;
}
The output of the above program would be:

--Incrementing pointer--
Address of a is 0x28ff24
Value of *a is 100
Address of a=a+1 is 0x28ff28
Value of *a is 200
Address of a++ is 0x28ff2c
Value of *a is 300
--Decrementing pointer--
Address of a is 0x28ff34
Value of *a is 500
Address of a=a-1 is 0x28ff30
Value of *a is 400
Address of a-- is 0x28ff2c
Value of *a is 300
--Comparing pointer--
Address of data[0] = 0x28ff24
Value of data[0] = 100
Address of data[1] = 0x28ff28
Value of data[1] = 200
Address of data[2] = 0x28ff2c
Value of data[2] = 300
Address of data[3] = 0x28ff30
Value of data[3] = 400
Address of data[4] = 0x28ff34
Value of data[4] = 500

In this above example variable a is a pointer to an integer array data.



Related topics:
Pointers in C   |   Pointer to an Array in C   |   Returning Array from a Function in C   |   Array of Pointers in C   |   Pointer to Pointer in C   |   Pointers and Functions in C

List of topics: C Programming

No comments:

Post a Comment