Pointer arithmetic in C language

To execute arithmetic operations on pointers in the C programming language, utilize pointer arithmetic. The size of the data type to which the pointer points impacts whether the address value is increased or decreased when we perform arithmetic operations on pointers.

The size of an integer in memory is normally 4 bytes, therefore if we have an integer pointer and we increment the pointer, it will shift to the following integer location in memory.

Example:

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *p = arr;

    printf("Value at p = %d\n", *p);
    printf("Value at p+1 = %d\n", *(p+1));
    printf("Value at p+2 = %d\n", *(p+2));
    printf("Value at p+3 = %d\n", *(p+3));
    printf("Value at p+4 = %d\n", *(p+4));

    return 0;
}

Output:

Value at p = 10
Value at p+1 = 20
Value at p+2 = 30
Value at p+3 = 40
Value at p+4 = 50

This example uses the five-element integer array arr. A pointer p is initialized to point to the array’s first entry. The values of the array items are then accessed using p and pointer arithmetic.

When we print the value at p, it displays the array’s 10 as its first element. The value at position p+1 prints the value of the array’s second element, which is 20. In the same way, printing the value at p+2 prints the array’s third element’s value, 30, and so on.

By deducting an integer value from the pointer, one can decrement the pointer using pointer arithmetic. By doing this, you can access earlier elements of an array by moving the pointer backward in memory.

Pointer arithmetic can be hazardous if used carelessly and can result in unpredictable behavior if we try to access memory outside of an array’s allocated bounds or point to invalid memory locations.