Skip to content
StudyFame

Introduction to Data Structures in C

A program is only as good as the way it stores its data. A phone's contact list, a printer's job line, the "undo" button and Google Maps routes all use a different way of organising data. Each of these ways is called a data structure.

In this lesson you will learn what a data structure is, the difference between linear and non-linear structures, the main types (array, linked list, stack, queue, tree, graph, hash table), the basic operations and the Big-O idea used to compare them. The rest of this module builds each one in C.

What You Will Learn

  • What a data structure and an abstract data type (ADT) are.
  • Primitive vs non-primitive, linear vs non-linear structures.
  • Where each common data structure is used in real life.
  • The basic operations: traverse, insert, delete, search, sort.
  • How Big-O notation describes speed.
  • Why C programs build data structures with structs and pointers.

Introduction to Data Structures in C Explained

Exam definition: A data structure is a particular way of organising and storing data in memory so that it can be accessed and modified efficiently. Data structures are classified as primitive (int, char, float, pointers) and non-primitive; non-primitive structures are either linear (elements form a sequence: array, linked list, stack, queue) or non-linear (elements form a hierarchy or network: tree, graph). An abstract data type (ADT) describes what operations a structure supports, not how they are implemented.

Memory trick: Data structures are ways of arranging things at home. A shoe rack with numbered slots = array. A train of coaches joined by hooks = linked list. A pile of plates = stack (last in, first out). A ticket queue = queue (first in, first out). A family tree = tree. A city road map = graph. A labelled cupboard where you jump straight to "Socks" = hash table.

Classification of data structures

Data Structures
├── Primitive: int, char, float, double, pointer
└── Non-primitive
    ├── Linear (one after another)
    │   ├── Array
    │   ├── Linked list (singly, doubly, circular)
    │   ├── Stack (LIFO)
    │   └── Queue (FIFO), circular queue
    └── Non-linear (hierarchy / network)
        ├── Tree (binary tree, binary search tree)
        └── Graph
    (Hash table: array + hash function, used for fast lookup)

Syntax: Building Blocks in C

C has no built-in list, stack or tree. You build them from arrays, structures and pointers, using malloc for memory:

int marks[100];                 /* array: fixed size, index access   */

struct node                     /* a "node" for linked structures    */
{
    int data;                   /* the value stored                  */
    struct node *next;          /* link to the next node             */
};

struct node *n = malloc(sizeof *n);   /* create a node at run time  */
n->data = 10;
n->next = NULL;                       /* NULL = end of the chain    */
StructureRuleReal-life use
ArrayFixed size, direct access by indexMarks of 60 students, image pixels
Linked listNodes joined by pointers; grows and shrinksMusic playlist, browser history
StackLast In, First Out (LIFO)Undo/redo, function calls, bracket checking
QueueFirst In, First Out (FIFO)Printer jobs, CPU scheduling, ticket booking
TreeParent–child hierarchyFolders on a disk, family tree, database indexes
GraphNodes connected by edgesMaps and routes, social networks
Hash tableKey → slot by a hash functionDictionaries, login lookup, caches

Example 1: The Same Data in an Array and a Linked List

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

int main(void)
{
    int arr[3] = {10, 20, 30};
    struct node *head = NULL, *n, *p;
    int i;

    /* Build the list 10 -> 20 -> 30 by adding at the front, from the end */
    for (i = 2; i >= 0; i--)
    {
        n = malloc(sizeof *n);
        if (n == NULL)
            return 1;
        n->data = arr[i];
        n->next = head;
        head = n;
    }

    printf("Array      : ");
    for (i = 0; i < 3; i++)
        printf("%d ", arr[i]);
    printf("\narr[2]     : %d (direct access)\n", arr[2]);

    printf("Linked list: ");
    for (p = head; p != NULL; p = p->next)
        printf("%d -> ", p->data);
    printf("NULL\n");
    printf("3rd node   : %d (reached by following 2 links)\n", head->next->next->data);

    while (head != NULL)          /* free every node */
    {
        n = head->next;
        free(head);
        head = n;
    }
    return 0;
}

Output

Array      : 10 20 30
arr[2]     : 30 (direct access)
Linked list: 10 -> 20 -> 30 -> NULL
3rd node   : 30 (reached by following 2 links)

Code Explanation

  1. The array stores the three values side by side in one block. arr[2] jumps straight to the third value: direct (random) access.
  2. Each linked-list node is a separate block created by malloc, holding a value and a pointer to the next node.
  3. Adding at the front (n->next = head; head = n;) from the last value to the first builds 10 → 20 → 30.
  4. To reach the third node, the program must follow links: head->next->next. This is sequential access.
  5. The final loop frees every node; otherwise the memory would leak.

How We Compare Data Structures: Big-O

Time complexity describes how the number of steps grows as the number of elements n grows. It is written in Big-O notation:

Big-ONameSteps for n = 1,000Example
O(1)Constant1Array access arr[i]
O(log n)Logarithmicabout 10Binary search
O(n)Linear1,000Linear search, traversing a list
O(n log n)Linearithmicabout 10,000Merge sort
O(n²)Quadratic1,000,000Bubble sort

Array vs linked list

OperationArrayLinked list
Access the i-th elementO(1)O(n)
Insert/delete at the beginningO(n) (shift elements)O(1)
SizeFixed (unless reallocated)Grows and shrinks freely
Extra memoryNoneOne pointer per node
Memory layoutOne continuous blockNodes scattered in memory
#include <stdio.h>

int linear_steps(const int a[], int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
        if (a[i] == key)
            return i + 1;              /* comparisons made */
    return n;
}

int binary_steps(const int a[], int n, int key)
{
    int low = 0, high = n - 1, steps = 0, mid;
    while (low <= high)
    {
        mid = (low + high) / 2;
        steps++;
        if (a[mid] == key)
            return steps;
        if (a[mid] < key)
            low = mid + 1;
        else
            high = mid - 1;
    }
    return steps;
}

int main(void)
{
    static int a[1000];
    int i;

    for (i = 0; i < 1000; i++)
        a[i] = i * 2;                  /* sorted: 0, 2, 4, ..., 1998 */

    printf("Search 1998 in 1000 sorted numbers\n");
    printf("Linear search steps: %d\n", linear_steps(a, 1000, 1998));
    printf("Binary search steps: %d\n", binary_steps(a, 1000, 1998));
    return 0;
}

Output

Search 1998 in 1000 sorted numbers
Linear search steps: 1000
Binary search steps: 10
  • Linear search checks every element: O(n), here 1000 comparisons.
  • Binary search halves the range each time: O(log n), here only 10 comparisons.
  • Choosing the right data structure and algorithm can make a program 100 times faster without a faster computer. (Both searches are explained in Linear and Binary Search in C.)

Important Points to Remember

  • A data structure = a way to organise data for efficient access and change.
  • Linear: array, linked list, stack, queue. Non-linear: tree, graph.
  • Stack = LIFO, Queue = FIFO.
  • Arrays give O(1) access but fixed size; linked lists give cheap insert/delete but O(n) access.
  • Basic operations: traverse, insert, delete, search, sort.
  • In C, data structures are built from structs, pointers and malloc; always free what you allocate.

Common Mistakes Beginners Make

MistakeWhat happensFix
Calling a stack "FIFO"Wrong exam answerStack = LIFO, queue = FIFO
Using a linked list when you need a[i] oftenSlow O(n) access every timeUse an array for index access
Forgetting next = NULL on the last nodeTraversal runs into garbageAlways end the chain with NULL
Not freeing nodesMemory leakFree every node before exit
Binary search on unsorted dataWrong resultsSort first, or use linear search

Data Structures Practice Questions

  1. What is a data structure? Why do we need it?
  2. Differentiate between linear and non-linear data structures with examples.
  3. What is an abstract data type?
  4. Compare an array and a linked list on access, insertion and memory.
  5. What does O(log n) mean? Give an example.
Show answers
  1. A way of organising and storing data so it can be used efficiently; the right structure makes operations faster and code simpler.
  2. Linear: elements in a sequence (array, linked list, stack, queue). Non-linear: hierarchy or network (tree, graph).
  3. A description of a data type by its operations (what it does), independent of its implementation; e.g. a Stack ADT has push, pop and peek.
  4. Array: O(1) access, costly insert/delete, fixed contiguous memory. Linked list: O(n) access, O(1) insert/delete at a known spot, dynamic size, extra pointer per node.
  5. Steps grow with the logarithm of n, i.e. the problem is halved each step; binary search.

Coding Exercise

Using struct node, build a linked list of the numbers 5, 15, 25, 35 (in that order), print it, print the number of nodes and their sum, then free all nodes.

Show solution
#include <stdio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

int main(void)
{
    int values[] = {5, 15, 25, 35};
    struct node *head = NULL, *tail = NULL, *n, *p;
    int i, count = 0, sum = 0;

    for (i = 0; i < 4; i++)            /* add at the end, using a tail pointer */
    {
        n = malloc(sizeof *n);
        if (n == NULL)
            return 1;
        n->data = values[i];
        n->next = NULL;
        if (head == NULL)
            head = n;
        else
            tail->next = n;
        tail = n;
    }

    for (p = head; p != NULL; p = p->next)
    {
        printf("%d ", p->data);
        count++;
        sum += p->data;
    }
    printf("\nNodes: %d, Sum: %d\n", count, sum);

    while (head != NULL)
    {
        n = head->next;
        free(head);
        head = n;
    }
    return 0;
}
5 15 25 35
Nodes: 4, Sum: 80

Quick Quiz: Data Structures (MCQ)

  1. Which is a non-linear data structure?

    A) Stack   B) Queue   C) Tree   D) Array

  2. A stack works on the principle:

    A) FIFO   B) LIFO   C) Random   D) Sorted order

  3. Accessing the 50th element of an array takes:

    A) O(1)   B) O(n)   C) O(log n)   D) O(n²)

  4. Which structure best represents a road map?

    A) Queue   B) Graph   C) Stack   D) Array

  5. The time complexity of binary search is:

    A) O(n)   B) O(n²)   C) O(log n)   D) O(1)

Show answers
  1. C: tree.
  2. B: LIFO.
  3. A: O(1).
  4. B: graph.
  5. C: O(log n).

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Data structureWay to organise data for efficient use
LinearArray, linked list, stack, queue
Non-linearTree, graph
Stack / QueueLIFO / FIFO
ADTDefined by its operations, not implementation
Array accessO(1); list access O(n)
Binary searchO(log n), needs sorted data

Frequently asked questions

What is a data structure in C?
A way of storing and organising data (built with arrays, structs and pointers) so that it can be accessed and modified efficiently.
What are the types of data structures?
Primitive and non-primitive; non-primitive are linear (array, list, stack, queue) and non-linear (tree, graph).
When should you use a linked list instead of an array?
When the size changes often and you insert/delete a lot, but rarely need access by index.

Remember

  • Rack, train, plates, queue, family tree, road map, labelled cupboard.
  • Pick the structure for the operation you do most.

Next Topic

Next lesson: Singly Linked List in C. You will build a singly linked list and write insert, delete, search and display functions.