c-example-demonstarte-of-dynamic-structure-with-pointer
admin
Diagram explaining dynamic data structures with linked memory blocks and pointers
Dynamic data structures are a cornerstone of efficient programming, especially when dealing with variable-sized data sets. Unlike static data structures that require predefined sizes, dynamic data structures allocate memory as needed, ensuring optimal memory usage. This article delves into the fundamentals of dynamic data structures and provides a practical implementation example.
Dynamic data structures allocate memory from the heap as required during program execution. These structures link memory blocks using pointers, creating flexible structures that can grow or shrink at runtime. Once a memory block is no longer needed, it is returned to the heap for reuse, optimizing memory utilization.
Below is a simple C program that demonstrates the creation of a dynamic data structure using the malloc
function for memory allocation and free
for deallocation:
#include<stdio.h>
#include<stdlib.h>
struct student {
int sno, m;
char sname[20];
float per;
};
void main() {
struct student *p;
// Allocating memory dynamically for a student structure
p = (struct student *) malloc(sizeof(struct student));
if (p == NULL) {
printf("Memory allocation failed!\n");
return;
}
// Input student details
printf("\nEnter student number, marks, and name: ");
scanf("%d %d %s", &p->sno, &p->m, p->sname);
// Calculate percentage
p->per = p->m / 3.0;
// Display student details
printf("\nStudent Details:\n");
printf("Number: %d\nMarks: %d\nName: %s\nPercentage: %.2f\n", p->sno, p->m, p->sname, p->per);
// Freeing allocated memory
free(p);
}
malloc
function dynamically allocates memory for a struct student
.free
function ensures that the allocated memory is returned to the heap, preventing memory leaks.Dynamic data structures are extensively used in:
Dynamic data structures provide the flexibility and efficiency required to manage complex and variable data. They form the backbone of many modern applications and programming paradigms. As demonstrated, their implementation involves dynamic memory allocation and proper memory management, ensuring optimal performance.
Start exploring dynamic data structures in your projects to leverage their potential for creating robust and efficient applications!