Pointer Arithmetic in C

Pointer Arithmetic refers to operations performed on pointers to navigate memory locations. Since pointers store memory addresses, they allow arithmetic operations to traverse elements in arrays or access memory systematically.

Definition

Pointer arithmetic enables pointers to move across elements of data structures like arrays. The type of the pointer determines how many bytes to move forward or backward during such operations.

Syntax:

                        
pointer_name++;  // Move to the next element
pointer_name--;  // Move to the previous element
pointer_name + n;  // Move forward by n elements
                        
                    

Operations on Pointers

Common pointer arithmetic operations include:

Example 1: Incrementing a Pointer

In this example, we use a pointer to traverse an integer array using pointer arithmetic.

Example:

                        
#include <stdio.h>
int main() 
{
    int arr[] = {10, 20, 30, 40};
    int *ptr = arr;  // Pointer to the first element
        
    for (int i = 0; i < 4; i++) {
    printf("Value at position %d: %d\n", i, *ptr);
    ptr++;  // Move to the next element
    }
        
return 0;
}
                        
                    

Output

Value at position 0: 10
Value at position 1: 20
Value at position 2: 30
Value at position 3: 40

Example 2: Pointer Difference

This example demonstrates calculating the difference between two pointers to determine the number of elements between them.

Example:

                        
#include <stdio.h>
int main() 
{
    int arr[] = {10, 20, 30, 40};
    int *start = &arr[0];  // Pointer to the first element
    int *end = &arr[3];    // Pointer to the last element
        
    printf("Distance between pointers: %ld\n", end - start);
        
    return 0;
}
                        
                    

Output

Distance between pointers: 3

Key Points