C++ · Module 7 · Lesson 41 min read

Pointer Arithmetic & Arrays

Arrays and pointers

An array name decays to a pointer to its first element:

ini
int arr[5] = { 10, 20, 30, 40, 50 };
int* p = arr;        // same as &arr[0]

Pointer arithmetic

ExpressionMeaning
p + iaddress of the i-th element after p
*(p + i)same as p[i]
p++move to the next element
q - pnumber of elements between them (type std::ptrdiff_t)
p < qcompare positions (same array only)

p + 1 moves by sizeof(*p) bytes: 4 for int, 8 for double, the size of the struct for structs.

Equivalences

arr[i] ≡ *(arr + i) ≡ *(i + arr) ≡ i[arr] (legal but don't write it!)

Walking with pointers

c
for (int* it = arr; it != arr + 5; ++it) std::cout << *it;

arr + 5 is the one-past-the-end pointer: valid to compute and compare, not to dereference. STL iterators copy this exact design: begin() and end().

C strings

A const char* points to characters ending with '\0':

c
const char* s = "Hi";
while (*s) { std::cout << *s; ++s; }

Rules ⚠️

  • Only do arithmetic within one array (and one past the end)
  • Going outside = undefined behaviour
  • Pointer arithmetic on void* isn't allowed

std::span (C++20, <span>) ✅

A safe view of contiguous elements (pointer + size):

c
void print(std::span<const int> data);   // accepts C arrays, std::array, std::vector

It never loses the size and supports range-for, size(), subspan().

Example

C++
#include <iostream>
#include <span>
#include <vector>

double sum(std::span<const double> values) {           // works with any contiguous sequence
    double total = 0;
    for (double v : values) total += v;
    return total;
}

std::size_t my_strlen(const char* s) {
    const char* start = s;
    while (*s != '\0') ++s;                            // walk until the terminator
    return static_cast<std::size_t>(s - start);       // pointer difference = number of chars
}

int main() {
    int arr[5] = { 10, 20, 30, 40, 50 };
    int* p = arr;                                       // decays to &arr[0]

    std::cout << "*p = " << *p << ", *(p + 2) = " << *(p + 2) << ", p[4] = " << p[4] << '\n';
    std::cout << "2[arr] = " << 2[arr] << " (legal, but please don't)\n";

    std::cout << "walk:";
    for (int* it = arr; it != arr + 5; ++it) std::cout << ' ' << *it;
    std::cout << '\n';

    int* first = &arr[1];
    int* last = &arr[4];
    std::cout << "elements between: " << last - first << '\n';

    double prices[] = { 99.5, 250, 1200 };
    double* dp = prices;
    std::cout << "double* + 1 moves "
              << reinterpret_cast<char*>(dp + 1) - reinterpret_cast<char*>(dp) << " bytes, int* + 1 moves "
              << reinterpret_cast<char*>(p + 1) - reinterpret_cast<char*>(p) << " bytes\n";

    std::vector<double> bills = { 1500, 800, 2200 };
    std::cout << "sum(array) = " << sum(prices) << ", sum(vector) = " << sum(bills)
              << ", sum(first two) = " << sum(std::span(bills).first(2)) << '\n';

    std::cout << "my_strlen(\"BudgetBuddy\") = " << my_strlen("BudgetBuddy") << '\n';

    const char* word = "C++";
    for (const char* c = word; *c; ++c) std::cout << '[' << *c << ']';
    std::cout << '\n';
    return 0;
}

/* Output:
*p = 10, *(p + 2) = 30, p[4] = 50
2[arr] = 30 (legal, but please don't)
walk: 10 20 30 40 50
elements between: 3
double* + 1 moves 8 bytes, int* + 1 moves 4 bytes
sum(array) = 1549.5, sum(vector) = 4500, sum(first two) = 2300
my_strlen("BudgetBuddy") = 11
[C][+][+]
*/