🔴 Advanced · Lesson 46
Dynamic Structures
Dynamic Structures
Dynamic Structures
Dynamic structures are structure variables created at run time using dynamic memory allocation. They are useful when the number of records is decided during execution.
Single struct allocation
C Language
#include <stdio.h>
#include <stdlib.h>
struct Student {
int roll;
char name[30];
float marks;
};
int main() {
struct Student *s = (struct Student*) malloc(sizeof(struct Student));
if(s == NULL) return 1;
s->roll = 101;
sprintf(s->name, "Aman");
s->marks = 88.5;
printf("%d %s %.1f", s->roll, s->name, s->marks);
free(s);
return 0;
}Array of structures dynamically
C Language
struct Student *students;
int n;
scanf("%d", &n);
students = malloc(n * sizeof(struct Student));
for(int i = 0; i < n; i++) {
scanf("%d %s %f", &students[i].roll, students[i].name, &students[i].marks);
}
free(students);Arrow Operator
| Expression | Meaning |
|---|---|
s.roll | Use when s is a structure variable |
s->roll | Use when s is a pointer to structure |
(*s).roll | Same as s->roll |
Summary
- Dynamic structure is allocated using
malloc - Use
->operator with structure pointer - Array of structures can be allocated dynamically
- Always check allocation failure
- Always free allocated memory
Dynamic Structures
Dynamic structures run time पर memory allocate करके बनाए जाते हैं। जब records की संख्या पहले से fixed न हो, तब ये useful होते हैं।
Single struct allocation
C Language
struct Student *s = malloc(sizeof(struct Student)); s->roll = 101; s->marks = 88.5; free(s);
Array of structures
C Language
struct Student *students; students = malloc(n * sizeof(struct Student)); free(students);
Arrow Operator
| Expression | Meaning |
|---|---|
s.roll | Structure variable के साथ |
s->roll | Structure pointer के साथ |
(*s).roll | s->roll जैसा ही |
सारांश
- Dynamic structure malloc से allocate होती है
- Structure pointer के साथ -> use करें
- Records run time पर create कर सकते हैं
- Allocation fail check करें
- free करना जरूरी है