Pointer Arithmetic in C

Pointer arithmetic in C allows you to perform arithmetic operations on pointers, such as adding or subtracting integers to/from pointers, which is useful when working with arrays and memory management. It allows you to navigate through memory locations efficiently.

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer to the first element of the array

printf("Initial address: %p\n", ptr);

// Move the pointer to the next element
ptr++;

printf("After incrementing: %p\n", ptr);

// Access and print the value at the new location
printf("Value at the new location: %d\n", *ptr);

// Subtract 2 from the pointer to go back two elements
ptr -= 2;

printf("After decrementing by 2: %p\n", ptr);
printf("Value at the new location: %d\n", *ptr);

return 0;
}

Output:

Initial address: 0x7ffeedf020
After incrementing: 0x7ffeedf024
Value at the new location: 20
After decrementing by 2: 0x7ffeedf01c
Value at the new location: 10

In this example:

  1. We declare an integer array arr with five elements and a pointer ptr pointing to the first element of the array.
  2. We use the printf function to display the memory address of the pointer ptr before and after performing arithmetic operations.
  3. Initially, ptr points to the first element of the array (10).
  4. We increment ptr by 1, effectively moving it to the next element in the array (20).
  5. We access and print the value at the new location, which is 20.
  6. We then subtract 2 from the pointer, which moves it back two elements in the array to the first element (10).

Pointer arithmetic is a powerful feature in C and is often used when iterating through arrays, working with dynamic memory allocation, or manipulating memory addresses efficiently. It's essential to be cautious with pointer arithmetic to ensure that you stay within the bounds of allocated memory to avoid undefined behavior.