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:
- Incrementing a pointer to point to the next memory location.
- Decrementing a pointer to point to the previous memory location.
- Adding an integer to a pointer to move forward by a specified number of elements.
- Subtracting an integer from a pointer to move backward by a specified number of elements.
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
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
- Pointer arithmetic depends on the data type of the pointer, as it determines the size of each step.
- Pointer arithmetic is commonly used for traversing arrays and performing operations on contiguous memory.
- Subtracting two pointers gives the number of elements between them, not the byte difference.
- Incorrect pointer arithmetic can lead to accessing invalid memory locations, causing undefined behavior.