What are Data Structures in C?

Learn via video courses
Topics Covered

Data Structures in C

Data Structures in C is a way of storing and organizing data in the computer memory so that it can be processed efficiently. In computer science, data structures play a foundational role in helping arrange data in memory for efficient processing. Using the data structures in C, we can make our program to be able to utilize the memory efficiently as well as improve it'’s performance.

data structures in c

Depending on how the elements are organized into the memory, data structures can be broadly classified into two types you're interested in deeper software concepts, you may also want to explore reverse engineering in software engineering.

  1. Primitive Data Structures Primitive Data Structures These are the data types which are defined by the C programming language. Primitive types can only store a value of single type. These are also known as system-defined data types. int, float, char, double are some primitive types of data types. Primitive data structures in C include int, char, float, double, and pointers.

system-defined data types. int, float, char, double are some primitive types of data types. 3. Non-Primitive Data structures These are the data structures in C which are derived from the primitive data types. Non-primitive data structures are also known as user-defined data types. Non-primitive data structures in C are able to store values of multiple data type. Arrays, trees, stack, queue, etc. are some of the user defined data structures in C.

These are considered basic data structures, and there are different data structures for various use cases, each designed to optimize the way data is managed and accessed.

Further the non-primitive data structures in C can be classified into two categories:

  1. Linear data structures: Data is stored and accessed in a sequential manner.
  2. Non-Linear data structures: Data is stored and accessed in a non-linear fashion.The implementation of non-linear data structures is generally more complex than that of linear data structures.

The above can be further classified into more specific types. Following is a list of some data structures we have in C:

  • Array data structure
  • Stack data structure
  • Queue
  • Linked List
  • Tree
  • Graph data structure

We will now look into each of these data structures that what they are, how they store data differently and when to use which of these data structures in C.The data stored in each structure can be managed and accessed in unique ways, depending on the requirements of the application.

Data Structures in C

Let us now go through the most common types of Data structures in C.

Arrays are a fundamental data structure in C, where each element stored must be of the same type. For example, an array of integers can be declared as int data[10];, and you can access each element using an index like int i = 0; data[i] = 5;.

Dynamic data structures, such as linked lists, stacks, and queues, can resize during program execution. This means they can adjust their memory space as needed, which enhances flexibility and efficiency when manipulating data stored in these structures.

Basic Data Structure Operations

Understanding basic data structure operations is essential for anyone working with the C programming language or any other programming language. These operations form the backbone of how we organize, store, and manipulate data efficiently, enabling us to solve complex problems and build robust applications.

  • At the core, basic operations include insertion, deletion, searching, and traversal. These are fundamental actions that can be performed on both primitive data structures (like int, char, and float) and non primitive data structures (such as arrays, linked lists, stacks, queues, trees, and graphs). For primitive data types, operations like assignment and comparison are the building blocks of more complex manipulations.

  • In linear data structures like arrays and linked lists, basic operations are typically performed in a sequential manner. For example, arrays allow constant time access to any element using its index, making operations like searching and updating data values straightforward. However, arrays are static data structures, meaning their size is fixed at creation, so inserting or deleting elements may require shifting data items and can be less efficient.

  • Dynamic data structures like linked lists, on the other hand, allow for flexible memory usage. In a singly linked list, each node contains data and a pointer to the next node, enabling efficient insertion and deletion at any position without the need for contiguous memory locations. Traversal in linked lists involves moving from the head node through each subsequent node until the desired data element is found or the end of the list is reached.

  • Stack data structures operate on the Last-In-First-Out (LIFO) principle, supporting basic operations such as push (inserting an element at the top) and pop (removing the topmost element). These operations are crucial for managing function calls, expression evaluation, and implementing undo features in applications.

  • Queue data structures follow the First-In-First-Out (FIFO) principle, with enqueue (inserting at the rear) and dequeue (removing from the front) as their primary operations. Queues are widely used in operating systems for task scheduling and resource management.

  • When it comes to non linear data structures, such as trees and graphs, basic operations become more complex. In a tree data structure, operations like insertion, deletion, and traversal (preorder, inorder, postorder) are used to organize and retrieve data efficiently. The root node serves as the starting point for accessing all the elements in a hierarchical data structure, making trees ideal for applications like file systems and database indexing.

  • Graph data structures consist of nodes connected by edges, representing relationships between data elements. Basic operations include adding or removing nodes and edges, as well as traversing the graph using algorithms like depth-first search (DFS) and breadth-first search (BFS). These operations are vital for internet indexing services, social networks, and solving complex problems involving interconnected data.

  • Advanced data structures like binary search trees combine the hierarchical nature of trees with efficient searching, insertion, and deletion operations, making them suitable for applications that require fast data retrieval, such as database management systems.

Finally, abstract data types (ADTs) provide a way to define and manipulate data structures independently of their implementation, allowing developers to create custom data structures and operations tailored to specific needs.

In summary, mastering basic data structure operations is crucial for organizing and manipulating data efficiently in C and other programming languages. Whether you are working with static or dynamic data structures, linear or non linear data structures, understanding these operations will empower you to build scalable, high-performance applications and tackle a wide range of real-world challenges.

Array (linear data structure)

An array data structure is a non-primitive linear data structure used for storing elements of the same datatype. All elements in an array are of the same type, which allows for efficient memory usage and easy manipulation. The array elements gets continuous memory allocation when stored, with each element stored at a specific index. Each element in an array is assigned a position known as index using which it can be accessed. Arrays support random access, allowing direct retrieval of any element by its index in constant time (O(1)). Elements can also be accessed sequentially using a loop.

In C programming language we have two types of arrays.

  • Single Dimensional array Also known as 1-D array used to store the elements in a single row. All the elements in the 1-D array gets continuous memory locations. The index for a single dimensional array will always start from 0 and end at n-1, where n is the size of the array. Syntax for declaring and initializing a single dimensional array in C:

    Any element is a one dimensional array can be accessed using the array name and it's index enclosed within the square brackets. In the below figure if I want to access the integer value 1 stored at index 2, we can do it as follows:

    one dimensional arrays Learn more about One Dimensional Arrays

  • Multidimensional array

    • A multidimensional array in C can be visualized as an array of arrays. Two dimensional arrays, three dimensional arrays are the types that come under this category.
    • Two dimensional array can be though of as an array consisting of two or more one dimensional arrays.
    • Each element in a 2D array is accessed using two indexes - one corresponds to row and the other corresponds to the column.
    • In 2D arrays also, indexing for both row and column starts from 0.
    • The elements in a 2D array in C can be accessed using the array, followed by row index number and column index number, each enclosed within the square brackets. If we want to access the element 5 stored at row 1 and column 2 we can do that as follows:

multidimensionals array

  • Similarly Three dimensional array can be considered as an array of two or more two dimensional arrays.
  • Each element in a 3D array is accessed using three indexes one corresponds to row, second corresponds to the column and the third one corresponds to the index number of the 2 dimensional array. Learn more about Multidimensional Arrays

To understand how operating systems manage memory and some of the challenges involved, including thrashing in OS, check out our detailed explanation.

Stack (stack data structure)

stack examples

A stack is a linear data structure in C in which insertion and deletion of an element is done at the same end, called top. It follows Last in First Out(LIFO) or First In Last Out(FILO) as the last element which is inserted is the one that comes out first. Stack consists of two main operations

  • push: Adding elements to the top of the stack In C, this is typically implemented using a void push function, which checks for overflow, updates the top index, and stores the new element at that position in the stack array.
  • pop: Removing elements from the top of the stack

In real world scenario, we see the stack pattern in our day to day life. Like we visit some restaurants and see plates kept stacked onto one another. The waiter pick up the plate from the top and brings it to our table. This is a pop operation. And after washing a plate it is put onto another plate, this refers to push operation in stack. In context of programming application, the use of stacks includes undo operation in MS Word, going back to the visited pages in the browser, and many more. Learn more about Stacks

Queue data structure

queue-example

A queue is also linear data structure in C in which insertion is done at one end called rear and the deletion at other end called front. Queue follows First In First Out(FIFO) or Last In Last Out(LILO), that means the first element which was inserted will be the first one to be deleted. Queue consists of two main operations:

  • EnQueue: Inserting an element at the rear(end) of the queue.In C, this is typically implemented as a function with a void return type, such as void enqueue, which inserts an element into the queue.
  • DeQueue: Removing and then returning the element at the front of the queue.

Talking about the real world scenarios, we see queue at the ticket counters when the person at the front of the queue is served first(FIFO) and person at the end of the queue is served at last(LILO). In programming, our operating system makes use of queues in some task scheduling algorithms. When we call for customer support, the waiting time depends on our position in a queue. Learn more about Queue data structure

Linked List

linked list types

Linked List is a linear data structure in C used to store a collection of data. Linked List is made up of nodes where each node contains a data field and pointer field(s). The pointer field(s) is used to link the nodes to each other and can vary in number depending upon the type of Linked List. It also has one pointer called head that always points to the first node of the Linked List. Linked List consists of three main operations data structures can be randomly updated while the program is running, which is efficient given how memory-intensive the code is.

  • Insert: Adding/Insert an element or new node to a list.
  • Delete: Removing and returning the element at the specified position from the list.
  • Traversal: Traversing the list.

There are three types of Linked List:

  • Singly Linked List: In this data structure in C, each node consists of a data field and a pointer that stores the reference to the next node. The pointer field of the last node of a singly linked list is always null. Only forward traversal is possible. Learn more about Singly Linked List
  • Doubly Linked List: In this each node consists of two pointers and one data field. One pointer points to the next node and the other points to the previous node. Traversal can be done forward as well as backward. Learn more about Doubly Linked List
  • Circular Linked List: It can be a singly linked list or a doubly linked list in which the last node pointer field contains the reference of the first node. Circular linked list does not contain any null field therefore, traversal can be done from any node in the list. Learn more about Circular Linked List

The application of Linked List includes implementing other data structures like stack and queue using it, in image viewer for navigating back and forth, in brower for navigating to previously visited page and next page and many more.

Tree

tree examples

A tree is a non-linear data structure in C. It follows a hierarchical pattern in which each node points to a number of nodes. The root node is the one which has no parent node and the leaf nodes are the ones with no child nodes. The basic operations that tree involves are choice of data structure can significantly affect the efficiency of algorithms and the overall performance of applications.

  • Inserting a data node into the tree
  • Deleting a node from the tree
  • Searching an element in the tree
  • Tree traversal (You can practice these operations using an Online JavaScript Compiler

There are various types of trees but let's discuss some most commonly used ones.

  • Binary Tree: A tree is known as a binary tree if each of its node have either exactly two child nodes, one child node or zero child. Each node in a binary tree consists of a data field, a pointer to the right child, and another pointer to the left child.
  • Binary Search Tree: A Binary Search Tree or BST is similar the Binary Tree except that in this we have some constraints over the nodes. In BST, all the left subtree elements must be less than the root and all the right subtree elements must be greater than the root node. This makes the searching operation for an element faster.

The application of trees can be found in various algorithms like Huffman coding, where tress are used for implementing logic for data compression. We can also see their use in expression evaluation by the compilers and many more areas.

Graph data structure

graph example

A graph is a non-linear data structure in C consisting of pair(V,E), where V is known as set of vertices and E corresponds to collection of pair of vertices called edges which connects any two vertices. The vertices are actually the nodes that have the data and pointer fields. A graph can be either directed or undirected.Different data structures are suited for different types of applications, and understanding their characteristics is essential for effective programming. The main operations on graphs are:

  • Adding and removing a vertex in the graph.
  • Adding or removing the edge in the graph.
  • Searching for an element in the it.
  • Checking if there exists a path from one vertex to another.

One common way to represent the relationships between vertices in a graph data structure is by using an adjacency matrix. An adjacency matrix is a square 2D matrix where each element indicates the presence or weight of an edge between nodes, making it easy to check connections between any two vertices.

When implementing a graph data structure in C, it is common to use a 'struct graph' to define the structure of the graph, including its vertices and edges. The number of vertices is typically managed using an integer variable such as 'int v', which helps in organizing and scaling the graph.

In real life we find the usage of graphs at many places like the google maps that we use for navigation makes use of graphs. Another application of graph is a social media. Social media shows us the mutual friends using the graphs only.

Unlock the Power of Efficient Coding! Join Our DSA Course Today and Transform Your Problem-Solving Abilities. Enroll Now!

Conclusion

  • Data structures in C is a way of storing and organizing data in the computer memory so that it can be processed efficiently.
  • Data structures can be broadly classified into two categories - Primtive and Non-Primitive.
  • Non-primitive data structures can be further classified into two categories - Linear and Non-linear.
  • Linear data structures include arrays, stacks, queues, linked list and Non-linear data structures include trees and graphs.
  • Each data structure has its own unique way of storing and processing data and are used according to the need of the situation.
  • Arrays are a type of non-primitive linear data structure of similar data types stored in a contiguous manner and can be further classified into single dimensional and multidimensional array and in this article we learnt about 2-D and 3-D arrays.
  • Stack is a linear data structure which works on the principle of Last In First Out(LIFO)and it is used in various real life applications like undo. Queue is also a linear data structure and works on the principle of First in First Out(FIFO).
  • Linked list ia a linear data structure in which data is not stored in a contiguous manner and consists of nodes which has data and pointer and can be further classified into single , double and circular linkedlist.
  • Then we come to non linear data structures in which first is tree which follows a hierarchial pattern which means there is a concept of parent node and child nodes and trees can be further classified into binary tree and binary search tree.
  • Another non-linear data structure is graph which is comprised of edges and vertices and it is used in real world applications like social media.