C Structures and Dynamic Memory

📌 C Structures and Dynamic Memory Allocation
C Structures and 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) |
