Pointers and Memory

Pointer Arithmetic

Adding one to a typed pointer advances by one complete element, not one byte.

What is Pointer Arithmetic?

Adding one to a typed pointer advances by one complete element, not one byte.

Walk through contiguous array storage with pointers and iterators.

Important points

  • Every pointer must refer to a live compatible object or be null.
  • Pair each owned allocation with exactly one release.
  • Prefer clear ownership and const-correct interfaces.

C and C++ code examples

C
Run code →
main.c
#include <stdio.h>

int main(void) {
    int values[] = {10, 20, 30, 40};
    int sum = 0;
    for (int *p = values; p < values + 4; ++p) sum += *p;
    printf("sum=%d distance=%td\n", sum, (values + 4) - values);
    return 0;
}
Expected output
sum=100 distance=4
C++
Run code →
main.cpp
#include <iostream>
#include <vector>

int main() {
    std::vector values{10, 20, 30, 40};
    int sum = 0;
    for (auto it = values.begin(); it != values.end(); ++it) sum += *it;
    std::cout << "sum=" << sum << " distance="
              << std::distance(values.begin(), values.end()) << '\n';
}
Expected output
sum=100 distance=4

C and C++ comparison

Pointer arithmetic is only defined within the same array or one position past it. C++ iterators express the same traversal and work across many container types.

C

Ownership and cleanup are conventions enforced by the programmer.

C++

Containers and RAII types can encode ownership and cleanup in object lifetimes.

Practice exercises

Run both versions, then modify them to observe the different language guarantees.

  • Test null and allocation-failure paths.
  • Run with AddressSanitizer and UndefinedBehaviorSanitizer.
  • Document whether every pointer owns or only observes its object.