student@ubuntu:~$
c 4/5 40 XP

Struct Pointers

0%

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) or sizeof(*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 = *p1 copies bytes but not pointed-to data. If the struct has pointers, both structs share the data.

Unlocks

Complete this skill to see what it unlocks.