Reading — step 1 of 5
Read
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 isT*ifx : T.*p— dereference: result type isTifp : T*; error ifpisn'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 isTifarr : 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:
| Expression | Required type | Result type |
|---|---|---|
&e | any lvalue | pointer to type(e) |
*e | pointer to T | T |
e1[e2] | array of T + int | T |
Concrete errors that real compilers emit:
error: indirection requires pointer operand— you wrote*xfor a non-pointerx.error: subscripted value is not an array, pointer, or vector— you wrotex[3]for a scalarx.
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…