C++

Pointer Arithmetic in C++

Pointer Arithmetic is a unique feature of C++ that allows you to perform arithmetic operations (like addition and subtraction) on pointer variables. Unlike standard math, adding 1 to a pointer doesn't just add one to the value; it moves the pointer to the next memory address based on the data type it points to.

1. The Theory: Scaling and Data Types

Theoretically, pointer arithmetic is governed by the size of the data type. The compiler automatically scales the arithmetic operation based on the result of the sizeof() operator for that specific type.

The Scaling Rule:

If you have a pointer ptr of type T, and you perform ptr + n, the new address is calculated as:

$$\text{New Address} = \text{Current Address} + (n \times \text{sizeof(T)})$$
  • Integers: If an int is 4 bytes and ptr is at address 1000, ptr + 1 results in address 1004.

  • Characters: If a char is 1 byte, ptr + 1 results in address 1001.

  • Doubles: If a double is 8 bytes, ptr + 1 results in address 1008.

2. Valid Operations in Pointer Arithmetic

Not all mathematical operations are allowed on pointers. Theoretically, only operations that make sense in the context of memory navigation are permitted:

  1. Increment (++): Moves the pointer to the next element.

  2. Decrement (--): Moves the pointer to the previous element.

  3. Addition (+): Moves the pointer forward by $n$ elements.

  4. Subtraction (-): Moves the pointer backward by $n$ elements.

  5. Pointer Subtraction (ptr2 - ptr1): Calculates the number of elements (not bytes) between two pointers of the same type.

Forbidden Operations: You cannot multiply or divide pointers, nor can you add two pointers together. Adding two memory addresses is logically meaningless.

3. Long Theory: The Pointer-Array Relationship

One of the most important concepts in C++ is that Array names act as constant pointers to their first element.

A. Array Decay

When you declare int arr[5], the name arr is essentially a pointer to &arr[0].

  • arr + 1 is the same as &arr[1].

  • *(arr + i) is exactly the same as arr[i].

B. Traversal Efficiency

Theoretically, using pointer arithmetic to traverse an array can be slightly faster than using array indexing ([]) because indexing requires the CPU to perform an addition and a multiplication for every access. By using ptr++, the CPU simply increments the current address, which is a very "cheap" operation at the hardware level.

4. Practical Code Example

This program demonstrates navigating an array using only a pointer and arithmetic.

#include <iostream>
using namespace std;

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

    cout << "Initial value (*ptr): " << *ptr << " at address: " << ptr << endl;

    // Moving forward using increment
    ptr++; 
    cout << "After ptr++: " << *ptr << " at address: " << ptr << endl;

    // Moving forward by 2 elements using addition
    ptr = ptr + 2; 
    cout << "After ptr + 2: " << *ptr << " at address: " << ptr << endl;

    // Subtraction to find distance
    int* startPtr = &arr[0];
    int* endPtr = &arr[4];
    cout << "\nElements between end and start: " << (endPtr - startPtr) << endl;

    return 0;
}

5. Potential Dangers (Long Theory)

Pointer arithmetic gives you the power to bypass the logical structure of your data, which leads to two major theoretical risks:

  • Walking off the Cliff: If you increment a pointer past the end of an array, C++ will not stop you. You will be pointing at "Random Memory." Reading this is a Logical Error; writing to it is a Crash/System Security Risk.

  • Type Mismatch: If you cast a pointer to a different type (e.g., casting an int* to a char*) and perform arithmetic, the "steps" the pointer takes will be wrong for the original data. This is often used in low-level systems programming to inspect individual bytes of an integer.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now