Back to Blog

C in 100 Seconds: Structs and Pointers | Episode 24

Daryl WongDaryl Wong

Video: C in 100 Seconds: Structs and Pointers — The Arrow Operator | Episode 24 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Structs and Pointers — The Arrow Operator

C in 100 Seconds, Episode 24


Last episode we learned structs — grouping data with the dot operator. But when you have a pointer to a struct, the dot doesn't work. You need the arrow.

The Arrow Operator

The arrow -> is shorthand for dereferencing a pointer and accessing a member:

Person *ptr = &alice;
ptr->name   // same as (*ptr).name
ptr->age    // same as (*ptr).age

The arrow dereferences and accesses in one step. Much cleaner than the alternative.

Passing Structs to Functions

Pass a pointer to modify the original struct — not a copy:

void birthday(Person *p) {
  p->age++;
}

birthday(&alice);  // alice.age is now 26

Without the pointer, the function would get a copy and the original wouldn't change.

Structs on the Heap

Allocate a struct with malloc. The result is already a pointer — use the arrow directly:

Person *bob = malloc(sizeof(Person));
strcpy(bob->name, "Bob");
bob->age = 30;
free(bob);

Stack structs use the dot. Heap structs use the arrow. The arrow works whenever you have a pointer to a struct.

Full Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  char name[50];
  int age;
} Person;

void birthday(Person *p) {
  p->age++;
}

int main() {
  Person alice = {"Alice", 25};
  Person *ptr = &alice;

  printf("Name: %s\n", ptr->name);
  printf("Age:  %d\n", ptr->age);

  birthday(&alice);
  printf("After birthday: %d\n", alice.age);

  Person *bob = malloc(sizeof(Person));
  strcpy(bob->name, "Bob");
  bob->age = 30;
  printf("\nHeap: %s, %d\n", bob->name, bob->age);
  free(bob);

  return 0;
}

Compile and run:

gcc structptr.c -o structptr
./structptr

Next episode: Unions — shared memory, one field at a time.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode24