$ solutions
Drill 1: Basic Address & Dereference
Original Ask: Declare an int, a pointer to it, and print its value, address, and dereferenced value.
int example = 10;
int *ptr = &example;
printf("%d\n", example); // prints 10
printf("%p\n", &example); // address of example
printf("%p\n", ptr); // ptr holds same address
printf("%d\n", *ptr); // dereference = 10
Explanation: ptr
is a “map” to the variable’s house. *ptr
says “go inside the house and look at the value.”
Drill 2: Swap Two Ints
Original Ask: Write a swap function that takes two pointers and swaps their values.
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Explanation: We pass the addresses of a
and b
. Dereferencing lets us change the original variables directly.
Drill 3: Array Decay & Pointer Arithmetic
Original Ask: Show that arr
is equivalent to &arr[0]
, and use pointer arithmetic to access the 2nd element.
int testarray[4] = {1, 2, 3, 4};
printf("testarray is stored at %p\n", testarray);
printf("&testarray[0] is %p\n", &testarray[0]);
printf("testarray[1] = %d\n", testarray[1]);
printf("*(testarray + 1) = %d\n", *(testarray + 1));
Explanation: Arrays “decay” into pointers. Indexing (arr[1]
) and pointer arithmetic (*(arr + 1)
) both access the same element.
Drill 4: Structs & the ->
Operator
Original Ask: Create a struct, make a pointer to it, and access a member using ->
.
struct Character {
char name[20];
int hp;
char class[20];
};
struct Character Benadryl = {"Benadryl", 100, "Wizard"};
struct Character *benadryl_ptr = &Benadryl;
printf("Benadryl’s Class is %s\n", benadryl_ptr->class);
Explanation: ->
means “follow the map to the struct, then go to this member.”
Drill 5: Stack Frame Addresses
Original Ask: Write a function with a local int, print its address, and call it multiple times to see how stack frames move.
void stack_frame() {
int local_int = 15;
printf("local_int is stored at %p\n", &local_int);
}
stack_frame();
stack_frame();
stack_frame();
Explanation: Each function call pushes a new stack frame. The local variable’s address changes as old frames are popped and new ones pushed.
⬅ Back to practice drills.