C Structures and Dynamic Memory

C Tutorial

📌 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:

OperatorUsage
.Access using structure variable
->Access using structure pointer

Example:

(*s).roll // same as
s->roll

📌 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:

Free inner pointer(s) → then free the struct pointer

📝 Summary Table

ConceptExample
Allocate struct memoryptr = malloc(sizeof(struct MyStruct));
Access dataptr->member
Allocate array of structsmalloc(n * sizeof(struct MyStruct))
Resize struct arrayrealloc(ptr, newSize)
Free memoryfree(ptr); (and internal pointers if any)

You may also like...