C Dynamic Struct Allocation
In this page:
Dynamically Allocating a Struct
A struct can be dynamically allocated on the heap using malloc(sizeof(struct StructName)), which reserves exactly enough memory to hold one instance of that struct, accessed through a pointer.
Example: Dynamically Allocating a Struct
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
struct Point *p = malloc(sizeof(struct Point));
p->x = 5;
printf("%d", p->x);
free(p);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Members with ->
The -> operator accesses a member of a struct through a pointer in a single step, combining what would otherwise be a dereference followed by the dot operator, written as (*p).member.
Example: Accessing Members with ->
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
struct Point *p = malloc(sizeof(struct Point));
p->x = 10;
printf("%d", p->x);
free(p);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Allocating an Array of Structs
An entire array of structs can be dynamically allocated at once by multiplying sizeof(struct StructName) by the desired element count, and each struct in the array is then accessed with regular indexing.
Example: Allocating an Array of Structs
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
struct Point *points = malloc(3 * sizeof(struct Point));
points[1].x = 7;
printf("%d", points[1].x);
free(points);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Freeing a Dynamically Allocated Struct
A dynamically allocated struct, whether a single instance or an array of them, is released with a single call to free, exactly as with any other block of memory obtained from malloc.
Example: Freeing a Dynamically Allocated Struct
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
struct Point *p = malloc(sizeof(struct Point));
p->x = 1;
free(p);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Structs with Dynamically Allocated Members
When a struct contains a pointer member that itself points to separately allocated memory, such as a dynamically sized name string, that inner allocation must be freed first, followed by the struct itself, to avoid leaking the inner memory.
Example: Structs with Dynamically Allocated Members
#include <stdio.h>
#include <stdlib.h>
struct Person { char *name; };
int main() {
struct Person *p = malloc(sizeof(struct Person));
p->name = malloc(10);
free(p->name);
free(p);
printf("Freed inner then outer");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: