Skip to main content

Pointers and Arithmetic Workshop

Retrieval Prompts

  1. State the rule for what p + n means when p has type T *.
  2. Explain what & and * do, in one sentence each.
  3. Write from memory the difference between int *a[10] and int (*a)[10].
  4. State what p[i] is defined to mean in terms of * and +.
  5. Explain when comparing two pointers with < is undefined.

Compare and Distinguish

Separate these pairs clearly:

  • address (&x) versus value (*p)
  • pointer to array (int (*)[10]) versus array of pointers (int *[10])
  • T * versus T **
  • function pointer R (*f)(args) versus function designator R f(args)

Common Mistake Check

Identify the error in each line:

  1. char *s = "hello"; s[0] = 'H';
  2. int *p; *p = 10;
  3. int *f(void) { int x = 5; return &x; }
  4. int a[5]; memset(a, 0, 5);
  5. int a[5], *p = a; if (p + 10 < p) { ... }

Mini Application

For each snippet, first draw a memory diagram, then predict the output, then compile with gcc -Wall -Wextra -O1:

  1. int a[4] = {10, 20, 30, 40};
    int *p = a + 2;
    printf("%d %d %d\n", *p, p[-1], p[1]);
  2. int x = 5, y = 7;
    int *arr[] = { &x, &y };
    (*arr[0])++;
    printf("%d %d\n", x, y);
  3. int x = 42, *p = &x, **pp = &p;
    **pp = 100;
    printf("%d\n", x);
  4. int add(int a, int b) { return a + b; }
    int sub(int a, int b) { return a - b; }
    int (*fs[2])(int, int) = { add, sub };
    printf("%d\n", fs[1](10, 3));
  5. Tricky cast prediction:

    uint32_t x = 0x11223344;
    unsigned char *p = (unsigned char *)&x;
    printf("%02x%02x%02x%02x\n", p[0], p[1], p[2], p[3]);

    Predict on a little-endian machine. Is the hex string 11223344 or 44332211?

Lab Tasks

  • Implement my_strlen, my_strcpy, and my_strcmp using pointer arithmetic only (no array subscripting). Verify against strlen, strcpy, strcmp on 20 inputs.
  • Build a tiny "shell of function pointers": a table mapping command strings to void (*)(int, char **) handlers; parse the command, dispatch, and print a help message if the command is unknown.
  • Use a debugger: gdb ./program, set a breakpoint, print *p, print p, print &p. Get comfortable seeing pointer values and dereferencing them from the debugger.

Evidence Check

This page is complete only if, given a short snippet of pointer code, you can:

  • draw a correct memory diagram before running the code
  • predict the value of every *p-style expression
  • explain the type of every declaration out loud