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

#include <stdio.h>
#include <stdlib.h>
struct Student {
int roll;
float marks;
};int main() {
struct Student *s;

// Allocate memory
s = (struct Student *)malloc(sizeof(struct Student));

if (s == NULL) {
printf(“Memory allocation failed!\n”);
return 1;
}

s->roll = 10;
s->marks = 88.5;

printf(“Roll = %d\nMarks = %.2f\n”, s->roll, s->marks);

free(s); // Free memory

return 0;
}


๐Ÿง  Using -> Operator

When accessing structure members via pointer:

Operator Usage
. Access using structure variable
-> Access using structure pointer

Example:

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

๐Ÿ“Œ Dynamically Allocating an Array of Structs

#include <stdio.h>
#include <stdlib.h>
struct Employee {
char name[30];
float salary;
};int main() {
int n;
struct Employee *emp;

printf(“Enter number of employees: “);
scanf(“%d”, &n);

emp = (struct Employee *)malloc(n * sizeof(struct Employee));

if (emp == NULL) {
printf(“Memory allocation failed!\n”);
return 1;
}

for (int i = 0; i < n; i++) {
printf(“\nEnter name and salary for employee %d: “, i + 1);
scanf(“%s %f”, emp[i].name, &emp[i].salary);
}

printf(“\nEmployee Details:\n”);
for (int i = 0; i < n; i++) {
printf(“%s – %.2f\n”, emp[i].name, emp[i].salary);
}

free(emp);
return 0;
}


๐Ÿ” Using realloc() to Expand Struct Memory

emp = realloc(emp, newSize * sizeof(struct Employee));

Example:

emp = realloc(emp, (n + 2) * sizeof(struct Employee));

๐Ÿšจ Struct with Pointer Members (Deep Copy Required)

Sometimes a struct contains pointer members; then you must allocate memory inside the struct too.

struct Person {
char *name; // pointer inside struct
};
int main() {
struct Person *p = malloc(sizeof(struct Person));p->name = malloc(20 * sizeof(char)); // Allocate memory for name string

strcpy(p->name, “John Doe”);

printf(“Name: %s\n”, p->name);

free(p->name); // Free inner pointer
free(p); // Free struct memory

return 0;
}


๐Ÿงน Memory Cleanup Rule

If a struct contains dynamic memory pointers:

Free inner pointer(s) โ†’ then free the struct pointer

๐Ÿ“ 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)

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *