C Structures and Dynamic Memory
๐ C Structures and Dynamic Memory Allocation
Dynamic memory allocation can also be applied to structures, allowing flexible creation of objects at runtime.
This is useful when the number of elements is unknown during compile time.
โ Basic Example: Allocating Memory for a Struct
๐ง Using -> Operator
When accessing structure members via pointer:
| Operator | Usage |
|---|---|
. |
Access using structure variable |
-> |
Access using structure pointer |
Example:
๐ Dynamically Allocating an Array of Structs
๐ Using realloc() to Expand Struct Memory
Example:
๐จ Struct with Pointer Members (Deep Copy Required)
Sometimes a struct contains pointer members; then you must allocate memory inside the struct too.
๐งน Memory Cleanup Rule
If a struct contains dynamic memory pointers:
๐ Summary Table
| Concept | Example |
|---|---|
| Allocate struct memory | ptr = malloc(sizeof(struct MyStruct)); |
| Access data | ptr->member |
| Allocate array of structs | malloc(n * sizeof(struct MyStruct)) |
| Resize struct array | realloc(ptr, newSize) |
| Free memory | free(ptr); (and internal pointers if any) |
