02. Pointer Arithmetic & Array Equivalence in C

🟡 Difficulty: Intermediate | Type-Scaled Offset Scaling, ptr++ & Array Bracket Syntax

📖 Definition

Pointer arithmetic is the operation of adding or subtracting integer values to or from pointers in C. Crucially, pointer arithmetic is automatically scaled by the byte size of the target data type (sizeof(*ptr)). Adding 1 to an int* pointer advances its memory address by 4 bytes (on 32/64-bit systems), not 1 byte!

🎯 Why It Is Used

  • High-Speed Array Traversal: Traversing contiguous memory arrays using incrementing pointers (ptr++) without calculating bracket index offsets.
  • Sub-String & Buffer Slicing: Finding substrings or calculating element distance between two pointer markers (end_ptr - start_ptr).

⚙️ How It Works: The Array Equivalence Theorem

In C, array bracket indexing is defined directly in terms of pointer arithmetic:

arr[i]  <===>  *(arr + i)

Because addition is commutative (arr + i == i + arr), the expression i[arr] is completely valid and equivalent to arr[i] in C!

📝 Syntax

int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // 'p' points to arr[0]

p++;        // Advances 'p' by sizeof(int) = 4 bytes (now points to arr[1])
int val = *p; // Reads 20

ptrdiff_t diff = (arr + 4) - arr; // Returns 4 (element count difference, NOT byte count!)

🔀 Valid vs Illegal Pointer Arithmetic Operations

Operation C Syntax Example Valid? Result Type
Pointer + Integerptr + 3✅ ValidPointer (Advanced by 3 * sizeof(*ptr))
Pointer - Integerptr - 2✅ ValidPointer (Decremented by 2 * sizeof(*ptr))
Pointer - Pointerptr2 - ptr1✅ Validptrdiff_t (Number of elements between pointers)
Pointer + Pointerptr1 + ptr2❌ ILLEGAL!Compilation Error (Adding RAM addresses is meaningless)
Pointer * Integerptr * 2❌ ILLEGAL!Compilation Error

🌱 Beginner Example: Traversing Array via Pointer Increment

#include <stdio.h>

int main(void) {
    int numbers[5] = {11, 22, 33, 44, 55};
    int *ptr = numbers; // Points to numbers[0]

    printf("=== Traversing Array using ptr++ ===\n");
    for (int i = 0; i < 5; i++) {
        printf("Address: %p | Value: %d\n", (void*)ptr, *ptr);
        ptr++; // Advance to next int (adds 4 bytes to address)
    }
    return 0;
}

🌼 Intermediate Example: String Length via Pointer Subtraction

#include <stdio.h>
#include <stddef.h> // For ptrdiff_t

size_t custom_strlen(const char *str) {
    if (str == NULL) return 0;

    const char *ptr = str;
    while (*ptr != '\0') {
        ptr++;
    }

    // Pointer subtraction returns element distance between pointers!
    return (size_t)(ptr - str);
}

int main(void) {
    const char text[] = "Hello, C Pointers!";
    printf("String: \"%s\"\n", text);
    printf("Computed Length: %zu characters\n", custom_strlen(text));
    return 0;
}

🌲 Advanced Example: Commutative Indexing Proof i[arr]

#include <stdio.h>

int main(void) {
    int arr[] = {100, 200, 300, 400};

    printf("=== Array Equivalence Proof ===\n");
    printf("Standard Syntax arr[2] : %d\n", arr[2]);
    printf("Pointer Syntax *(arr+2): %d\n", *(arr + 2));
    printf("Commutative Syntax 2[arr]: %d\n", 2[arr]); // Equivalent!
    return 0;
}

🔍 Line-by-Line Explanation

  • ptr++: Adds sizeof(*ptr) bytes to the raw memory address stored in ptr.
  • (ptr - str): Subtracts two pointers into the same array, returning a signed ptrdiff_t value representing element count distance.
  • 2[arr]: Demonstrates that bracket notation A[B] is compiled strictly as *(A + B).

💻 Expected Terminal Output

=== Traversing Array using ptr++ ===
Address: 0x7ffd1020a100 | Value: 11
Address: 0x7ffd1020a104 | Value: 22
Address: 0x7ffd1020a108 | Value: 33
Address: 0x7ffd1020a10c | Value: 44
Address: 0x7ffd1020a110 | Value: 55
String: "Hello, C Pointers!"
Computed Length: 18 characters
=== Array Equivalence Proof ===
Standard Syntax arr[2] : 300
Pointer Syntax *(arr+2): 300
Commutative Syntax 2[arr]: 300

⚠️ Common Mistakes & Pitfalls

  • Out-of-Bounds Pointer Dereferencing: Incrementing a pointer past the end of an array and dereferencing it triggers Undefined Behavior or Segmentation Faults.
  • Subtracting Pointers to Unrelated Objects: Subtracting pointers that do NOT point into the same array object is undefined behavior in ISO C.
  • Attempting Pointer Arithmetic on void*: ISO C forbids arithmetic on generic void* pointers because sizeof(void) is incomplete (GCC allows it as an extension, but strictly invalid under ISO C11).

📌 Important Rules & Limitations

  • Pointer arithmetic scales automatically by sizeof(*ptr).
  • Pointer subtraction (p2 - p1) returns a signed integer of type ptrdiff_t (from <stddef.h>).
  • You cannot add two pointers together (p1 + p2 is illegal).

🌐 Multilingual Explanation: English

Pointer arithmetic scales added integers by sizeof(*ptr). Bracket notation arr[i] is defined as *(arr + i). Pointer subtraction returns the distance between two pointers in elements.

🌐 Multilingual Explanation: Hindi (Roman Script)

Pointer arithmetic mein ptr + 1 karne par address 1 byte nahi, balki data type ke size ke barabar (jaise int ke liye 4 bytes) aage badhta hai. arr[i] aur *(arr + i) bilkul same hain.

🌐 Multilingual Explanation: Marathi (Roman Script)

Pointer arithmetic madhye ptr + 1 kelyas address data type chya size noosar aage jaato. arr[i] aani *(arr + i) ekach ahet.

❓ Practice Questions

  1. If int *p = 0x1000, what address does p + 3 evaluate to on a system where sizeof(int) == 4?
  2. Why is p1 + p2 illegal in C, while p1 - p2 is legal?
  3. What header file defines the ptrdiff_t type?

🚀 Practical Coding Challenge

Write a C program named pointer_array_copy.c that copies elements from a source array to a destination array using only pointer incrementing (*dest++ = *src++) inside a while loop without bracket indices.

🧭 Navigation & Breadcrumbs

← Previous: 01. Pointer Basics | Module 10 Guide | Next: 03. Double Pointers →