Pointer Arithmetic and Pointers with Arrays
In C, arrays and pointers are deeply intertwined. The name of an array is actually a constant pointer to its first element.
What is it?
Pointer arithmetic refers to adding or subtracting integers to/from pointers. When you add 1 to a pointer (`ptr + 1`), it doesn't add 1 byte—it advances by the size of the underlying data type!
Why is it used?
High-speed sequential array traversal and string processing in performance-critical code.
Detailed Explanation
How Pointer Arithmetic Works:
• If `int *p` points to address 1000, `p + 1` points to address 1004 (since `sizeof(int) == 4`).
• `*(arr + i)` is 100% equivalent to `arr[i]`!
• The compiler converts all array bracket notation `arr[i]` into `*(arr + i)` under the hood.
Syntax Structure
Syntax Blueprint
int *ptr = arr;
*(ptr + 1); // Accesses arr[1]
ptr++; // Advances to next element
Code Example
C Code
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int *ptr = numbers; // Array name 'numbers' decays to &numbers[0]
printf("=== Pointer Arithmetic Demonstration ===\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: Value = %d | Address = %p\n", i, *(ptr + i), (void*)(ptr + i));
}
// Advancing pointer directly with ptr++
printf("\n--- Walking pointer with ptr++ ---\n");
int *walker = numbers;
while (walker < numbers + 5) {
printf("%d ", *walker);
walker++; // Advances by 4 bytes each step
}
printf("\n");
return 0;
}
Explanation of the Code
• Notice each memory address increases by 4 bytes (e.g. ...30, ...34, ...38, ...3C, ...40).
• `*(ptr + i)` and `*walker++` demonstrate two idiomatic ways to traverse memory arrays in C.
Expected Output
=== Pointer Arithmetic Demonstration ===
Element 0: Value = 10 | Address = 0x...00
Element 1: Value = 20 | Address = 0x...04
Element 2: Value = 30 | Address = 0x...08
Element 3: Value = 40 | Address = 0x...0C
Element 4: Value = 50 | Address = 0x...10
--- Walking pointer with ptr++ ---
10 20 30 40 50
Real-World Application
Used across memory copy implementations (`memcpy`) and fast CPU audio/video codecs.
Common Mistakes to Avoid
• Incrementing past the bounds of the array and dereferencing invalid memory.
• Trying to reassign an array name (`numbers = ptr` is invalid because array names are constant pointers).
Quick Practice Challenge
Print the third element of an array using pointer notation `*(arr + 2)`.
Key Takeaways
• Pointer arithmetic scales automatically by the size of the data type.
• `arr[i]` is identical to `*(arr + i)`.
• The array name decays to a pointer to its first element.