Pointers and Arrays

Pointers and Arrays in C: An array is a street of identical houses. Indexing is standing at the corner and calling out a number: "house 3, please." Pointer…

The Analogy: Walking the Street Instead of Reading House Numbers

An array is a street of identical houses. Indexing is standing at the corner and calling out a number: "house 3, please." Pointer arithmetic is walking — you stand at one house and take a step, and a step always means one whole house forward, never one metre.

That is the crucial detail. p + 1 does not add one to the address; it adds the size of one element. For an int pointer the address moves four bytes, for a double pointer eight, for a char pointer one. The compiler knows the house size from the pointer's type and does the multiplication for you, which is why void * cannot participate: no house size, no step.

Once you accept that, a[i] stops being special syntax and becomes what it actually is — an abbreviation for "start at a, step i houses, look inside."


Syntax or Core Structure

#include <stdio.h>

int main(void) {
    int a[5] = { 10, 20, 30, 40, 50 };
    int *p = a;                 /* the array decays: p points at a[0] */

    printf("a[2]     = %d\n", a[2]);
    printf("*(p + 2) = %d\n", *(p + 2));
    printf("p[2]     = %d\n", p[2]);

    printf("*p       = %d\n", *p);
    p++;                        /* one element forward, not one byte */
    printf("*p       = %d\n", *p);

    printf("byte gap between a[0] and a[1] = %td\n",
           (char *)&a[1] - (char *)&a[0]);
    printf("elements from a to a + 5       = %td\n", &a[5] - &a[0]);
    return 0;
}

Output:

a[2]     = 30
*(p + 2) = 30
p[2]     = 30
*p       = 10
*p       = 20
byte gap between a[0] and a[1] = 4
elements from a to a + 5       = 5

The first three lines print the same value three ways, because they are the same expression. The language defines subscripting as a[i] == *(a + i), which has a famous and useless corollary: since addition commutes, 2[a] also compiles and yields 30. Never write it, but knowing why it works confirms you have the model right.

Note the two printed differences. Casting to char * before subtracting gives the gap in bytes — 4, one int. Subtracting the int pointers directly gives the gap in elements — 5. Pointer subtraction has type ptrdiff_t, which prints with %td.

The five equivalent traversals

size_t n = 5;

for (size_t i = 0; i < n; i++)          sum += a[i];          /* index */
for (size_t i = 0; i < n; i++)          sum += *(a + i);      /* explicit */
for (int *it = a; it != a + n; it++)    sum += *it;           /* half-open walk */
for (int *it = a; it < a + n; it++)     sum += *it;           /* same, with < */
for (int *it = a, *end = a + n; it != end; it++) sum += *it;  /* end hoisted */

All five are correct. The third is the one to internalise, because it != end with a half-open range is the shape the standard library and every C++ iterator uses, and it makes the off-by-one structurally impossible.


Technical Depth: Element Steps, and the Legal One Past the End

The step size is the type's size, so identical-looking arithmetic moves different distances:

Pointer typepp + 1p + 3
char *0x10000x10010x1003
int *0x10000x10040x100c
double *0x10000x10080x1018

This is why p + sizeof(int) is a bug rather than a clever trick: it advances four elements, sixteen bytes. The multiplication is already done for you.

One past the end is special

For int a[5], the standard explicitly permits you to form the address a + 5, and to compare it. Dereferencing it is undefined. a + 6 is undefined even to compute.

int *end = a + 5;                     /* legal, and the whole point */
for (int *it = a; it != end; it++)    /* legal: comparison only */
    printf("%d ", *it);
/* printf("%d", *end);                   undefined: never visit it */

That single guarantee is what makes half-open ranges work in C. An empty range is begin == end, a range of one is end - begin == 1, and no arithmetic ever strays outside the permitted region.

Pointers into different arrays do not relate

int a[4], b[4];
/* a - b            undefined: unrelated objects */
/* if (a < b)       undefined for ordering */
if (p == q) { }                       /* equality is always fine */

Subtraction and ordering are only defined for two pointers into the same array (or one past its end). In practice a comparison of unrelated pointers usually returns something, which is how "check whether this pointer is inside my buffer" ends up in codebases as an undefined-behaviour bug that happens to work.

The array is not the pointer, again

int a[5];
int *p = a;

sizeof a        /* 20: the whole array */
sizeof p        /* 8:  one address */
a = p;          /* error: an array is not assignable */
p = a;          /* fine: decay */
p++;            /* fine */
a++;            /* error: nothing to increment */

Inside a function that received int a[], all of the array-specific behaviour is gone — the parameter really is a pointer, so a++ compiles there and sizeof a is 8.

Walking a string is the same idea

size_t my_strlen(const char *s) {
    const char *start = s;
    while (*s != '\0') s++;           /* stop at the terminator */
    return (size_t)(s - start);       /* distance walked, in elements */
}

That is strlen, in three lines, and it explains why strlen is O(n): the length is not stored anywhere, it is measured by walking. Keeping start is the habit to notice — walk a copy, never lose the base address.

A row pointer for a 2D array

int grid[3][4];
int (*row)[4] = grid;                 /* pointer to an array of 4 ints */

row++;                                /* advances 16 bytes: one whole row */
int value = row[0][2];                /* grid[1][2] */

The parentheses matter: int (*row)[4] is a pointer to an array of four ints, while int *row[4] is an array of four pointers. Two completely different types, one pair of brackets apart.


Real World Example: Two-Pointer Compaction and Reversal, In Place

Filtering a collection without allocating anything is the classic two-pointer job: one pointer reads, one pointer writes, and because the writer never overtakes the reader they can share the same array. Reversal is its mirror image — two pointers closing in from the ends.

#include <stdio.h>

/* Keeps only the positive values, in order, at the front of a.
   Returns how many were kept. */
size_t keep_positive(int *a, size_t n) {
    int *write = a;
    for (const int *read = a; read != a + n; read++)
        if (*read > 0)
            *write++ = *read;
    return (size_t)(write - a);
}

void reverse(int *a, size_t n) {
    if (n < 2) return;
    int *lo = a;
    int *hi = a + n - 1;
    while (lo < hi) {
        int t = *lo;
        *lo++ = *hi;
        *hi-- = t;
    }
}

void show(const char *label, const int *a, size_t n) {
    printf("%-9s", label);
    for (const int *it = a; it != a + n; it++) printf("%3d", *it);
    putchar('\n');
}

int main(void) {
    int a[] = { 4, -2, 7, 0, -9, 3, 8 };
    size_t n = sizeof a / sizeof a[0];

    show("before:", a, n);

    size_t kept = keep_positive(a, n);
    show("kept:", a, kept);
    printf("         (%zu of %zu survived)\n", kept, n);

    reverse(a, kept);
    show("reversed:", a, kept);
    return 0;
}

Output:

before:    4 -2  7  0 -9  3  8
kept:      4  7  3  8
         (4 of 7 survived)
reversed:  8  3  7  4

Zero is dropped along with the negatives, because the test is > 0 — worth stating, since "positive" and "non-negative" being confused is a real bug in real filters.

Three things here are the transferable craft. The read pointer is const int *, so the compiler guarantees the scan cannot accidentally modify what it is examining, while the write pointer is plain int *. The loops end with read != a + n rather than an index comparison, so there is no separate counter to get wrong. And keep_positive returns the new count instead of trying to shrink the array, because a C array cannot shrink — the caller now treats the first kept elements as live and the rest as stale, which is exactly how every in-place filter in C works.

The reversal loop shows why *lo++ = *hi reads oddly but is safe: the assignment happens to the old lo, then lo advances. The two statements are separated by a semicolon, so there is no unsequenced-modification problem — which there would be if you tried to compress them into one expression.


Common Mistakes

  1. Adding bytes instead of elements. p + sizeof(int) moves four elements, not four bytes. The scaling is automatic; adding it yourself multiplies twice.
  1. Dereferencing the end pointer. *(a + n) is one past the last element. Forming that address is legal, visiting it is undefined. Only compare against it.
  1. Using <= in a pointer loop. for (int *it = a; it <= a + n; it++) visits n + 1 elements. Half-open != or < against a + n is correct.
  1. Comparing or subtracting pointers into different arrays. Undefined, and it usually returns a plausible number, which is worse than failing.
  1. Confusing *p++, (*p)++ and *++p. The first returns *p then advances the pointer; the second increments the pointed-at value; the third advances first and then reads. Add parentheses whenever the intent is not obvious at a glance.
  1. Losing the base pointer. Walking the only pointer you have to a buffer means you can no longer restart the scan — and if the buffer came from malloc, you can no longer free it. Walk a copy and keep the original.
  1. Calling sizeof inside a function that received the array. The parameter is a pointer there, so sizeof a / sizeof a[0] is 2 or 1, never the element count. The length must be a parameter.
  1. Expecting int ** to accept a 2D array. A row-major grid needs int (*)[COLS], or a flat int * with manual r * cols + c arithmetic.

Best Practices

  • Use the half-open idiom for (T *it = a; it != a + n; it++). The empty case, the single-element case and the off-by-one all take care of themselves.
  • Hoist a + n into a named end pointer when the loop body is long. It reads better and it is computed once.
  • Make the reading pointer const T * and leave only the writing pointer unqualified. In a two-pointer algorithm that distinction is free documentation and a compiler-checked promise.
  • Keep the base pointer untouched and walk a copy, especially for anything you will later free.
  • Use ptrdiff_t with %td for pointer differences, and size_t with %zu for counts and indices.
  • Pass the element count with every pointer to a sequence, immediately after it, so the pair reads as one argument.
  • Prefer indices over pointer walking when the index itself is meaningful — an error message that says "row 47" beats one that says "somewhere in the buffer".
  • Cast to char * before doing byte-level arithmetic, and never do arithmetic on a void *, which has no element size to scale by.

Practice Exercises

  1. Prove the scaling. Declare a char, an int and a double array of four elements each. For each, print the addresses of p, p + 1 and p + 3 as (void *), plus (char *)(p + 1) - (char *)p. Then explain in one sentence why the third column differs across the three types while the increment written in the source is identical.
  1. Write strlen and strcpy by hand. Implement size_t my_strlen(const char *s) and char *my_strcpy(char *dst, const char *src) using only pointer walking — no subscripts, no library calls. Test them against the real ones on an empty string, a one-character string and a twenty-character string, and confirm my_strcpy returns dst as the standard version does.
  1. Two pointers, one pass. Write size_t dedupe_sorted(int *a, size_t n) that removes consecutive duplicates from a sorted array in place using a read pointer and a write pointer, returning the new length. Test with {1,1,2,3,3,3,4,5,5} and confirm you get {1,2,3,4,5} and 5. Then confirm it handles n == 0 and a single element without a special case.
  1. Cross the line deliberately. Take the show function from the example and change its loop to it <= a + n. Run it, record the extra value printed, then rebuild with -fsanitize=address -g and record the report. Finally write down which of the two builds you would rather have discovered this in, and why the normal build's output was so unhelpful.