• Home
  • Pointer Basics – Pointer Traversal in Reverse Direction

Pointer Basics – Pointer Traversal in Reverse Direction

View Categories

Pointer Basics – Pointer Traversal in Reverse Direction

< 1 min read

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.



⚙️
main.c

Copy to clipboard

#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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *