Skip to content
Pointers, Arrays & Address Arithmetic
step 1/5

Reading — step 1 of 5

Read

~2 min readType Checking & IR

Pointers, Arrays & Address Arithmetic

C without pointers is not C. Pointers, arrays, and the conversions between them are the spine of the language and one of the trickier parts of the type system.

Pointer types

If T is a type, T * is "pointer to T". Operations:

  • &x — address-of: result type is T* if x : T.
  • *p — dereference: result type is T if p : T*; error if p isn't a pointer.
int  x = 42;
int *p = &x;     // p is int*
int  y = *p;     // *p is int

Array types

T arr[N] declares an array of N values of type T. Operations:

  • arr[i] — subscript: equivalent to *(arr + i); result type is T if arr : T[N].
  • In most contexts (function args, assignments) an array name decays to a pointer to its first element.

Type checker rules

When you see an expression, check the operator against the operand's type:

ExpressionRequired typeResult type
&eany lvaluepointer to type(e)
*epointer to TT
e1[e2]array of T + intT

Concrete errors that real compilers emit:

  • error: indirection requires pointer operand — you wrote *x for a non-pointer x.
  • error: subscripted value is not an array, pointer, or vector — you wrote x[3] for a scalar x.

Pointer arithmetic and stride

If p : T*, then p + 1 advances by sizeof(T) bytes, not by 1 byte. This is why int* and char* arithmetic differ. The codegen must scale subscript / arithmetic by element size:

arr[i]  ⇒  load_at( base_addr(arr) + i * sizeof(elem(arr)) )

This is purely a type-checker concern at this stage; we compute the right stride later in codegen.

What our exercise builds

A tiny type checker for declarations + a few operators. Input is a stream of declarations and queries; the checker outputs the type of each query or an error message. We use a textual format for types so the output is diffable:

int  ⇒  "int"
T*   ⇒  "ptr <T>"
T[N] ⇒  "arr <T> N"

References: chibicc type.c, Sandler Ch. 11–14 (pointers, arrays, structs), K&R §5 (pointers), C11 §6.3.2.1 (lvalue conversions).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…