Struct Pointers
Challenge Gallery
Quick Reference
Access syntax:
Student s; // Struct variable
s.name; // Dot access
Student *p = &s; // Struct pointer
p->name; // Arrow access (same as (*p).name)
Dynamic allocation pattern:
Student *s = calloc(1, sizeof(Student)); // Allocate + zero
if (s == NULL) { /* handle error */ }
s->age = 20;
strcpy(s->name, "Alice");
// ... use s ...
free(s);
Common Pitfalls
- sizeof(Type *) vs sizeof(Type) – The pointer size (8 bytes) is NOT the struct size. Always use
sizeof(Student)orsizeof(*p). - . vs -> – Dot for variables, arrow for pointers. Using the wrong one is a compile error.
- Forgetting to free – Dynamically allocated structs must be freed. Free inner allocations first, then the struct.
- Shallow copy –
*p2 = *p1copies bytes but not pointed-to data. If the struct has pointers, both structs share the data.