This example demonstrates how pointer arithmetic can be used to access array elements in reverse order. Instead of incrementing the pointer, the pointer is decremented to move backwards through memory.
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *ptr;
int i;
ptr = &arr[4];
for (i = 0; i < 5; i++)
{
printf("%d ", *ptr--);
}
printf("\n");
return 0;
}
Output:
50 40 30 20 10
ptr is initialized with the address of the last element of the array.
*ptr accesses the value at the current address, and ptr-- moves the pointer to the previous integer element.
Since ptr is an int *, decrementing the pointer moves the address backwards by sizeof(int) bytes.
In the expression *ptr--, dereferencing happens first using the current address, and the pointer is decremented afterwards.
This is equivalent to:
*(ptr--)
Pointer decrement is commonly used while traversing arrays in reverse order.