C Tutorial

Dynamic Data Structures in C


Introduction

Dynamic data structures in C allow you to create and manipulate data structures that can grow or shrink in size during runtime. This guide explores two common dynamic data structures: dynamic arrays and linked lists. Sample code is provided to demonstrate their usage.

Dynamic Arrays

A dynamic array is a resizable array that can grow or shrink as needed. In C, dynamic arrays are typically implemented using pointers and memory allocation functions like `malloc` and `realloc`. Here's a sample code that demonstrates dynamic array creation and usage:

#include <stdio.h> #include <stdlib.h> int main() { int *dynamicArray = NULL; int size = 0; // Initial allocation dynamicArray = (int *)malloc(sizeof(int)); if (dynamicArray == NULL) { perror(`Memory allocation failed`); exit(1); } // Add elements dynamicArray[size++] = 42; // Resize the array dynamicArray = (int *)realloc(dynamicArray, sizeof(int) * 2); if (dynamicArray == NULL) { perror(`Memory reallocation failed`); exit(1); } dynamicArray[size++] = 23; // Clean up free(dynamicArray); return 0; }

Linked Lists

A linked list is a data structure made up of nodes, where each node contains data and a reference to the next node. Linked lists are suitable for scenarios where data insertion and deletion are frequent. Here's a sample code that demonstrates a simple singly linked list:

#include <stdio.h> #include <stdlib.h> // Node structure for a singly linked list struct Node { int data; struct Node *next; }; int main() { struct Node *head = NULL; struct Node *newNode = (struct Node *)malloc(sizeof(struct Node)); if (newNode == NULL) { perror(`Memory allocation failed`); exit(1); } newNode->data = 42; newNode->next = NULL; head = newNode; // Add more nodes // Clean up while (head != NULL) { struct Node *temp = head; head = head->next; free(temp); } return 0; }

Conclusion

Dynamic data structures are crucial in C programming, allowing you to manage data efficiently during runtime. This guide introduced dynamic arrays and linked lists, along with sample code to demonstrate their usage. As you delve deeper into C programming, you'll discover more advanced dynamic data structures and their applications in various scenarios.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.