Memory
Heap Struct
A struct can also live in heap storage and be accessed through a pointer.
Heap Struct
heap_struct.c
#include <stdio.h>
#include <stdlib.h>
struct Box {
int width;
int height;
};
int main(void) {
int width = ;
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 = ;
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 = ;
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;
}
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.