Pointer arithmetic:
Incrementing a pointer –
We use the ++ to increment the pointer. Since pointers store addresses, it makes sense to increase a pointer only when we are making use of arrays.
Syntax for incrementing a pointer:

pointerName++

Let us look at the code snippet below to see how we can increment pointers:

#include <stdio.h>
 
int main () {
 
int  arr[] = {11, 12, 13};
int  i, *ptr;
 
ptr = arr; //pointer ptr points to the first location in the array
 
for ( i = 0; i < 3; i++) {
 
printf("Address of arr[%d] : %x\n", i, ptr );
printf("Value of arr[%d] : %d\n", i, *ptr );
 
ptr++; //move to the next location in array
}
return 0;
}
  • We have assumed that integer values are 32 bits.
  • Pointer ptr points to the first location in array
  • We are propagating through the array arr by moving to the next location in the array by incrementing the pointer.
  • Initially, the pointer points to the location where the first value in the array is stored.
  • Every time we increment the pointer, we are moving to the location of the next value in the array.

The output of the above code will be:

Address of arr[0] = 3ab6a954
Value of arr[0] = 11
Address of arr[1] = 3ab6a958
Value of arr[1] = 12
Address of arr[2] = 3ab6a95c
Value of arr[2] = 13

Decrementing a pointer –
Decrementing a pointer is the same as incrementing a pointer. We decrement the pointer in cases where are have the pointer point to an array.
Syntax for decrementing a pointer:

pointerName--

Let us look at the code snippet below to see how we can decrement pointers:

#include <stdio.h>
 
int main () {
 
int  arr[] = {11, 12, 13};
int  i, *ptr;
 
ptr = &arr[3-1]; // pointer points to the last location in the array
 
for ( i = 2; i >= 0; i--) {
 
printf("Address of arr[%d] : %x\n", i, ptr );
printf("Value of arr[%d] : %d\n", i, *ptr );
 
ptr--;//move to the previous location in the array
}
 
return 0;
}
  • We have assumed that integer values are 32 bits.
  • Pointer ptr points to the last location in array
  • We are propagating through the array arr in reverse orderby moving to the previous location in the array by decrementing the pointer.
  • Initially, the pointer points to the location where the last value in the array is stored.
  • Every time we increment the pointer, we are moving to the location of the previous value in the array.

 
The output of the above code will be:

Address of arr[2] : c7207c2c
Value of arr[2] : 13
Address of arr[1] : c7207c28
Value of arr[1] : 12
Address of arr[0] : c7207c24
Value of arr[0] : 11

[yuzo_views]












CopyRight © 2019

CopyRight © 2019