Pointer to struct in C: solved exercise
Pointer to struct in C: solved exercise
If you searched for a solved pointer to struct in C, here is the difference between value access (s.field) and pointer access (p->field), together with dynamic struct allocation using malloc.
The arrow operator -> is equivalent to dereferencing the pointer and accessing the field: p->field is syntactic sugar for (*p).field.
Problem statement
Define a Product struct with fields name (32-character string), price (double), and stock (int). Write a function that receives a pointer to Product, applies a percentage discount to the price, and decrements the stock by 1. Show the result with both static and dynamic access.
C solution
Expected output
Common mistakes
- Using
.instead of->with a pointer:p.pricewith aProduct *is a compile error;p->priceis required. - Not initializing all fields before printing:
mallocdoes not initialize memory; fields may contain garbage. - Not checking the return value of
malloc: if it returnsNULLand the pointer is dereferenced, the program crashes with a segmentation fault. - Forgetting
free(b)at the end: everymallocmust have a correspondingfreeto avoid memory leaks.
Practical use
Pointers to structs are the central pattern in C programming with complex data: linked lists, trees, hash tables, and software modules that pass large structures between functions without copying them. Passing const Product * is more efficient than passing Product by value when the struct is large.
Recommended next exercise
- const pointer in C: solved exercise
- Struct and files in C: solved exercise
- Calloc in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
When should I use a struct by value and when by pointer?
Use by value when the struct is small (1–2 numeric fields) and you do not need to modify it in the called function. Use by pointer when the struct is large (avoids copying), when you need to modify its fields in the function, or when it is a node of a dynamic structure (list, tree).
What is the difference between malloc(sizeof(Product)) and declaring Product b?
Product b allocates the struct on the stack, automatically freed when the block exits. malloc allocates on the heap, with a lifetime independent of the creating block, but requires explicit free. The heap is appropriate when the struct’s lifetime must outlast the function that created it.
Can you have an array of pointers to structs?
Yes: Product *catalog[100] is an array of 100 pointers, each pointing to an independently allocated Product. This is useful when structs have varying sizes (simulated inheritance via composition) or when you want to relocate them with realloc without invalidating external pointers.