Pointers and Arithmetic Workshop
Retrieval Prompts
- State the rule for what
p + nmeans whenphas typeT *. - Explain what
&and*do, in one sentence each. - Write from memory the difference between
int *a[10]andint (*a)[10]. - State what
p[i]is defined to mean in terms of*and+. - 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 *versusT **- function pointer
R (*f)(args)versus function designatorR f(args)
Common Mistake Check
Identify the error in each line:
char *s = "hello"; s[0] = 'H';int *p; *p = 10;int *f(void) { int x = 5; return &x; }int a[5]; memset(a, 0, 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:
-
int a[4] = {10, 20, 30, 40};
int *p = a + 2;
printf("%d %d %d\n", *p, p[-1], p[1]); -
int x = 5, y = 7;
int *arr[] = { &x, &y };
(*arr[0])++;
printf("%d %d\n", x, y); -
int x = 42, *p = &x, **pp = &p;
**pp = 100;
printf("%d\n", x); -
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)); -
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
11223344or44332211?
Lab Tasks
- Implement
my_strlen,my_strcpy, andmy_strcmpusing pointer arithmetic only (no array subscripting). Verify againststrlen,strcpy,strcmpon 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