A struct can also live in heap storage and be accessed through a pointer.

heap struct `malloc(sizeof(struct Box))` requests storage for one `struct Box`.
arrow access The arrow operator reads or writes fields through the struct pointer.

Heap Struct

width
heap_struct.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
#include <stdlib.h>

struct Box {
    int width;
    int height;
};

int main(void) {
    int width = 3;
    struct Box *box = (struct Box *)malloc(sizeof(struct Box));

    if (box == 0) {
        return 1;
    }

    box->width = width;
    box->height = 4;
    int area = box->width * box->height;

    printf("area=%d\n", area);
    free(box);
    return 0;
}
#include <stdio.h>
#include <stdlib.h>

struct Box {
    int width;
    int height;
};

int main(void) {
    int width = 5;
    struct Box *box = (struct Box *)malloc(sizeof(struct Box));

    if (box == 0) {
        return 1;
    }

    box->width = width;
    box->height = 4;
    int area = box->width * box->height;

    printf("area=%d\n", area);
    free(box);
    return 0;
}
#include <stdio.h>
#include <stdlib.h>

struct Box {
    int width;
    int height;
};

int main(void) {
    int width = 7;
    struct Box *box = (struct Box *)malloc(sizeof(struct Box));

    if (box == 0) {
        return 1;
    }

    box->width = width;
    box->height = 4;
    int area = box->width * box->height;

    printf("area=%d\n", area);
    free(box);
    return 0;
}
  1. width ← 3, box ← ⟨addr A⟩, box->width ← 3, box->height ← 4, area ← 12

    9int main(void) {10    int width→ 3 = 3; //@width=5, 711    struct Box *box→ ⟨addr A⟩ = (struct Box *)malloc(sizeof(struct Box));1213    if (box == 0) {14        return 1;15    }1617    box->width→ 3 = width3;18    box->height→ 4 = 4;19    int area→ 12 = box->width3 * box->height4;2021    printf("area=%d\n", area12);22    free(box⟨addr A⟩);23    return 0;24}
    outputarea=12
  1. width ← 5, box ← ⟨addr A⟩, box->width ← 5, box->height ← 4, area ← 20

    9int main(void) {10    int width→ 5 = 5;11    struct Box *box→ ⟨addr A⟩ = (struct Box *)malloc(sizeof(struct Box));1213    if (box == 0) {14        return 1;15    }1617    box->width→ 5 = width5;18    box->height→ 4 = 4;19    int area→ 20 = box->width5 * box->height4;2021    printf("area=%d\n", area20);22    free(box⟨addr A⟩);23    return 0;24}
    outputarea=20
  1. width ← 7, box ← ⟨addr A⟩, box->width ← 7, box->height ← 4, area ← 28

    9int main(void) {10    int width→ 7 = 7;11    struct Box *box→ ⟨addr A⟩ = (struct Box *)malloc(sizeof(struct Box));1213    if (box == 0) {14        return 1;15    }1617    box->width→ 7 = width7;18    box->height→ 4 = 4;19    int area→ 28 = box->width7 * box->height4;2021    printf("area=%d\n", area28);22    free(box⟨addr A⟩);23    return 0;24}
    outputarea=28