{ }codelper

C Pointer Practice Problems

Pointers don't really sink in from reading; you have to write them yourself. Work through these 16 problems in order, from passing an address to dynamic allocation.

16 problemsLevel 2–5Solve in C

1. Values and addresses #1–7

An argument passed to a function is a copy, so changing it inside the function leaves the outside variable as it was.
To change the outside variable, pass its address with &x and write *p = value inside the function.
That is exactly why you put & in scanf.

Syntax refresher: C Pointers Explained for Beginners

  1. Name tags pointing at the same list8P0262
  2. The robot that bounces back3P0203
  3. Lists inside lists and shallow copies8P0406
  4. Copied robots3P0076
  5. The all-or-nothing vending machine3P0382
  6. Slice views that share cells, and copies8P0439
  7. Cloned adventurers and a shared vault3P0159

2. Walking with a pointer #8–12

An array's name is used as the address of its first element.
p + 1 is not 1 byte further on but the next element, and *(p + i) means the same as p[i].
An array passed to a function becomes a pointer, so sizeof cannot tell you its length.
Pass the count along with it.

Syntax refresher: C Pointers Explained for Beginners · C Arrays: Declare, Initialize, and Loop

  1. Min, max and sum through pointers2P0073
  2. Walking to the longest run with pointers2P0074
  3. Detaching train cars with a pointer to a pointer2P0201
  4. A box ranking built from an array of pointers2P0246
  5. Cutting, pasting and reversing video clips with prev and next pointers2P0417

3. malloc and free #13–16

When the size has to be decided while the program runs, get the memory with malloc(n * sizeof(int)).
That memory holds garbage values, so fill it yourself or use calloc.
When you are done, give it back with free exactly once, and don't use the pointer after that.

Syntax refresher: C malloc() and free(): Dynamic Memory

  1. Keeping the words2P0075
  2. An array that doubles2P0158
  3. A table whose rows have different lengths2P0202
  4. A Tiny Heap Manager8P0365

Good to know

See also