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.
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
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
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
Good to know
- Reading
*pwhen the pointer was never given a value, or isNULL, usually causes a Segmentation fault. - Never
returnthe address of a local variable in a function. The variable is gone once the function ends. - In
int* a, b;, onlyais a pointer.bis a plainint.
See also
- C Array and String Practice Problems — 81 problems
- 100 C Programming Practice Problems for Beginners — 100 problems
- C Loop Practice Problems: for, while, do-while — 50 problems
- Learn C — lessons with explanations and examples
- C reference
- C error messages
- Other problem sets