Search⌘ K
AI Features

Passing Pointers to Struct

Explore how to pass pointers to structs in C, focusing on defining struct types, dynamic memory allocation with malloc, and accessing struct fields via pointers. Understand both explicit dereferencing and shorthand pointer usage with structs, and see how these concepts differ from using structs on the stack.

We'll cover the following...

Pointer to a struct

Pointers can also be used to point to a struct. Here is how this would be done:

C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int year;
int month;
int day;
} date;
int main(void) {
date *today;
today = malloc(sizeof(date));
// the explicit way of accessing fields of our struct
(*today).day = 21;
(*today).month = 5;
(*today).year = 2024;
// the more readable shorthand way of doing it
today->day = 21;
today->month = 5;
today->year = 2024;
printf("The date is %d/%d/%d\n", today->day, today->month, today->year);
free(today);
return 0;
}

Here’s a visualization of the code:

Variables declared in main are allocated on the stack before it is invoked
1 / 10
Variables declared in main are allocated on the stack before it is invoked

Refer to the slides above while we go through this example step by step.

  • On lines 4–8, we define a struct type ...