How to play with pointers in C


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Like ++, other arithmetic operators (--, +=, -=, +, -) work on pointers too as long as the pointer stays in the boundary of declared variables.

Following example output a string in reverse order:

Two pointers can also be subtracted from each other if the following conditions are satisfied:

  1. Both pointers will point to elements of same array; or one past the last element of same array
  2. The result of the subtraction must be representable in ptrdiff_t data type, which is defined in stddef.h. ptrdiff_t is a type of integer.

Using subtraction operation between two pointers we can get how far the elements are from each other in the array.

Warning: Care must be taken to make sure that the low address always gets subtracted from the high address. Otherwise, the behaviour will be undefined as illustrated in the example below:

#define ARRAY_SIZE 10

int arr[ARRAY_SIZE] = { 0 };

int *p = arr + 2;
int *q = arr + 6;

/* ptrdiff_t diff = p - q; */ /* Fatal: p - q < 0, it won't point within arr and the result may not fit in ptrdiff_t */
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content