1. Home
  2. Explore
  3. Computer Science
  4. C Data Structures and Pointers

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

C Data Structures and Pointers

Data Structures and Dynamic Memory in C

Pointers, Memory, and Indirection

A pointer is a variable that stores a memory address. A pointer to an integer can be declared with int *x; the asterisk in a declaration indicates that x is a pointer rather than an ordinary integer variable.

The memory pointed to by a pointer is sometimes called its pointee. A pointer and its pointee are separate things: declaring a pointer does not automatically allocate memory for the value it may eventually point to.

Allocating and accessing memory

The function malloc requests a block of memory of a specified size, measured in bytes. It returns the address of the allocated block, so that address must be stored in a pointer of a suitable type. The sizeof operator makes it possible to request the size of a type without having to assume a particular number of bytes.

For example, the following operations have distinct purposes:

  1. Declare an integer pointer.

  2. Allocate enough memory for an integer.

  3. Store the returned address in the pointer.

  4. Use the pointer to access the allocated integer.

The dereference operator, written * when used with a pointer expression, accesses the value at the address the pointer contains. Thus, if x points to an allocated integer, assigning to *x changes the integer stored at that address.

A pointer that has not been initialized may contain an unpredictable address. Dereferencing such a pointer can cause invalid memory access, often producing a segmentation fault. A pointer must point to valid allocated memory before its pointee is accessed.

Declaring a pointer creates the pointer variable; it does not create the memory that the pointer is meant to reference.

Aliasing: two pointers to the same memory

Assigning one pointer to another copies the address, not the pointed-to value. After y = x, both pointers refer to the same memory block. Writing through either pointer changes that shared value.

For example, if x and y point to the same integer, assigning 424242 through x and then 131313 through y leaves the integer equal to 131313. The second assignment overwrites the first.

This behavior is called aliasing: multiple pointers provide access to the same memory. It is useful, but it also means that an update through one pointer can affect what is observed through another.

Null pointers and character zero

NULL represents a pointer that does not point to a valid object. It is often used to represent an empty list or the end of a linked structure.

NULL is distinct in meaning from the null character, written '\0', which is a character value used, for example, to mark the end of a C string. Although both are represented by zero in common implementations, one is a pointer value and the other is a character value.

Structures, fields, and pointer access

A structure groups related fields into one custom data type. If a structure variable is accessed directly, the dot operator selects one of its fields. If a pointer points to a structure, the arrow operator selects a field through that pointer. In C, p->field is a convenient equivalent of (*p).field.

Structures and pointers are basic building blocks for many data structures: a structure defines what information each element contains, while pointers connect elements in memory.


Arrays and Dynamically Sized Memory

An array stores multiple values of the same type in a contiguous block of memory. Its size is fixed when it is created. Elements can be accessed directly by index, and the computer can jump to a given element without visiting the elements before it. This is called random access; it means direct access by index, not access in an unpredictable order.

Why fixed-size arrays can be difficult to grow

If an array’s allocated memory is immediately surrounded by memory that is already in use, the array cannot simply expand into the adjacent space. To make a larger array, a program may need to:

  1. Allocate a new, larger block of memory.

  2. Copy the existing elements into the new block.

  3. Store additional elements in the new space.

  4. Free the old block.

  5. Update the program’s pointer to refer to the new block.

If the old array contains nnn elements, copying them takes time proportional to nnn, so a resize operation can take O(n)O(n)O(n) time. This is the cost of growing an array when existing elements must be moved.

Using malloc memory as an array

A dynamically allocated block of memory can be used with array-style indexing. If malloc returns memory large enough for three integers, the pointer can be indexed as though it referred to an array of three integers.

The allocated values are contiguous. If an integer occupies four bytes on a particular computer, the second integer begins four bytes after the first, and the third begins eight bytes after the first. C’s indexing and pointer arithmetic account for the size of the pointed-to type, so index 111 refers to the next integer rather than the next byte.

A pointer returned by malloc therefore gives access to a contiguous block that can be indexed, even though it was not declared as a fixed-size array in the source code.

Memory-management practices

Memory allocation can fail. A call to malloc may return NULL, so programs should check the returned pointer before using it.

Memory allocated dynamically should be released with free when it is no longer needed. If the program overwrites its only pointer to an allocated block before freeing the block, that memory becomes unreachable to the program. This is a memory leak: the program can no longer access the allocation to use or release it.

Resizing with realloc

realloc can resize a block of dynamically allocated memory. It may enlarge or shrink the block and, when necessary, move its contents to a different location. This avoids writing the copying process manually.

A safe pattern is to store the result of realloc in a temporary pointer, check whether the result is NULL, and only then replace the original pointer. If a failed result is assigned directly over the original pointer, the original allocation’s address may be lost, creating a memory leak.

Even when realloc simplifies the code, resizing a block may still involve copying its contents. The operation is convenient, but it does not remove the underlying cost of moving data when the block cannot grow in place.


Linked Lists

A linked list stores values in separate nodes connected by pointers. Unlike an array, the nodes do not need to occupy adjacent memory locations. This allows the list to grow one node at a time without moving all its existing values.

A node for a list of integers typically contains:

  • An integer field holding the node’s value.

  • A pointer to the next node.

The first node is reached through a pointer often called the head or list pointer. The final node’s next pointer is NULL, marking the end of the list. An empty list is represented by a head pointer equal to NULL.

Self-referential structures

Each node needs a pointer to another node of the same type. In C, this requires naming the structure type before the short alias is available. A common definition is:

typedef struct node
{
    int number;
    struct node *next;
} node;

The structure is named struct node, and typedef creates node as a shorter alias for that type. Inside the definition, the next field is written as struct node *next because the alias is not available until the definition is complete.

Creating and linking nodes

To add a node, a program allocates enough memory for the entire structure, typically using sizeof on the node type. It checks that allocation succeeded, assigns values to the node’s fields, and updates the appropriate pointer or pointers to connect the new node to the list.

If a node is being appended, the previous final node’s next pointer is updated to point to it. The new final node’s next pointer is set to NULL.

To find the end of a list, a program can use a temporary pointer that begins at the head. It repeatedly follows next pointers until the next pointer is NULL. This process visits nodes one at a time; the list does not provide direct access to its middle or final node unless extra pointers are maintained.

Insertion and pointer-update order

Pointer updates must be made in an order that does not disconnect existing nodes from the list.

  • Insert at the beginning: The new node first points to the current head. Then the head is updated to point to the new node. If the head were overwritten first, the previous list could become unreachable.

  • Insert at the end: The new node is connected after the current final node, and its own next pointer is set to NULL.

  • Insert in the middle: The new node is first connected to the node that will follow it. Then the preceding node is updated to point to the new node.

For example, when inserting a node containing 333 between nodes containing 222 and 444, the new node must point to 444 before the node containing 222 is changed to point to the new node. Otherwise, the remaining list beginning at 444 could be orphaned.

Maintaining sorted order requires traversing the list until the correct insertion point is found. Inserting at the beginning is simpler, but it does not preserve sorted order unless the new value belongs there.

Performance trade-offs

A linked list can grow dynamically: adding a node requires allocating memory for the node and connecting it with pointers, rather than relocating all the existing elements.

However, a linked list loses an array’s random access. To reach a particular position, the program must follow pointers from the head, visiting nodes sequentially.

  • Search: In the worst case, every node must be visited, so searching takes O(n)O(n)O(n) time.

  • Finding an insertion point: If the list must remain sorted, traversal may take O(n)O(n)O(n) time.

  • Adding at the head: If the head pointer is available, inserting at the beginning takes O(1)O(1)O(1) time.

  • Indexed access: Reaching the element at a chosen position takes O(n)O(n)O(n) time in the worst case.

Because linked lists do not allow direct jumps to middle elements, they do not support ordinary binary search efficiently. Binary search depends on being able to access the middle element repeatedly.


Binary Search Trees

A binary search tree organizes nodes hierarchically. Each node has a value and up to two child pointers, conventionally called left and right. A node with no children is a leaf. The topmost node is the root, and a pointer to the root provides access to the rest of the tree.

The defining ordering rule is:

  • Every value in a node’s left subtree is smaller than the node’s value.

  • Every value in a node’s right subtree is greater than the node’s value.

A subtree is itself a tree, so this ordering rule applies recursively at every node.

Searching a binary search tree

To search for a target value:

  1. Start at the root.

  2. If the current pointer is NULL, the value is not in the tree.

  3. If the target is smaller than the current node’s value, continue in the left subtree.

  4. If the target is greater, continue in the right subtree.

  5. If neither comparison applies, the target equals the current value and has been found.

Each comparison eliminates one subtree from consideration. This is analogous to binary search: the tree’s structure lets the search choose a direction rather than checking every node.

Height and performance

The number of steps required to search a tree depends on its height, the longest downward path from the root. In a balanced tree, the height grows logarithmically with the number of nodes, so search can take O(log⁡n)O(\log n)O(logn) time.

A tree is not automatically balanced. If values are repeatedly inserted in an order that creates a long chain, the tree can become very tall. In that case, searching may take O(n)O(n)O(n) time. Balanced-tree algorithms rearrange links as elements are inserted so that the tree’s height remains controlled; such balancing is necessary to maintain logarithmic performance.

A binary search tree combines linked structures’ ability to add nodes without moving all existing values with a search order that can support fast lookup. The benefit depends on keeping the tree appropriately balanced.


Hash Tables

A hash table combines an array with a way to store multiple values associated with the same array position. A hash function takes an input, such as a name, and computes an array index, called a bucket. The array then provides direct access to the bucket.

For example, a simple hash function for names might use the first letter to select one of 262626 buckets. The computer can then jump directly to the selected bucket rather than searching through every stored name.

Collisions and chaining

A collision occurs when two different inputs produce the same bucket. With a first-letter hash function, all names beginning with the same letter collide.

One way to handle collisions is chaining: each array bucket points to a linked list containing all the values assigned to that bucket. The array provides direct access to the bucket, and the linked list holds any additional values that hash to the same index.

Searching then involves two stages:

  1. Apply the hash function to select a bucket.

  2. Search the linked list in that bucket.

If few values are in each bucket, this can be much faster in practice than searching one large list. If many values collide into the same bucket, however, the linked list becomes long and the search can take O(n)O(n)O(n) time in the worst case.

Hash functions and trade-offs

A simple hash function is easy to implement, but it may distribute values poorly. For example, using only the first letter can create a long chain if many names begin with the same letter.

Using more characters can reduce collisions, but it may require a much larger array of buckets. For two-letter combinations drawn from 262626 letters, there are 26×2626 \times 2626×26 possible combinations. More buckets use more memory, and they still do not guarantee that collisions will never occur.

A hash table’s performance therefore depends on both the hash function and how evenly it distributes inputs. In many practical cases, a well-designed hash table gives fast average lookup and insertion. Its worst case remains O(n)O(n)O(n) if many values end up in one bucket. A perfect mapping with no collisions would allow constant-time access, O(1)O(1)O(1), but achieving this reliably for arbitrary inputs is not generally guaranteed.


Tries

A trie is a tree-like structure designed to store strings, such as names or words. The name is derived from “retrieval.” In a common design, each node contains an array of pointers, with one position for each possible next character. For letters in the English alphabet, a node may have 262626 child positions.

To store a word, the trie follows one child for each character:

  1. Begin at the root.

  2. Follow the child corresponding to the first character.

  3. Continue through one child per remaining character.

  4. Mark the final node to indicate that a complete word ends there.

Different words can share the nodes for common prefixes. For example, names beginning with the same first letter share the initial branch; names with additional common letters share more of the path. A marker at the end distinguishes a complete word from a prefix that is only the beginning of another word.

Performance and memory use

Finding a word requires following a path whose length is determined by the word’s characters. If the word has length kkk, search and insertion take O(k)O(k)O(k) time. If the maximum word length is bounded by a fixed constant, this is effectively constant time with respect to the number of words stored: adding more words elsewhere in the trie does not require searching through them.

This speed requires substantial memory. Each node may reserve many child pointers even when only a few are used. Tries therefore trade memory for fast lookup and for efficient handling of shared prefixes.


Choosing a Data Structure

Different structures support different operations efficiently. No single structure is best for every situation.

Arrays

  • Strength: Contiguous storage and constant-time indexed access.

  • Limitation: A fixed-size array cannot grow without allocating a larger block; resizing may require copying, which takes O(n)O(n)O(n) time.

  • Search: A sorted array supports binary search in O(log⁡n)O(\log n)O(logn) time because its elements can be accessed by index.

Linked lists

  • Strength: Dynamic growth without relocating all existing elements.

  • Limitation: Elements must be reached by following pointers.

  • Search: O(n)O(n)O(n) in the worst case; direct indexed access and binary search are not efficient.

Binary search trees

  • Strength: Dynamic, ordered storage that can support search in O(log⁡n)O(\log n)O(logn) time when balanced.

  • Limitation: An unbalanced tree can degrade to O(n)O(n)O(n) operations and may behave like a linked list.

Hash tables

  • Strength: Direct access to a bucket, with fast average lookup when values are distributed well.

  • Limitation: Collisions require handling, and poor distribution can make operations O(n)O(n)O(n). Additional buckets can reduce collisions but consume memory.

Tries

  • Strength: Lookup and insertion depend on the length of the key, not directly on the number of stored keys.

  • Limitation: They can consume considerable memory because nodes reserve space for many possible character branches.

These comparisons illustrate a recurring principle: a data structure can spend memory or impose organizational constraints in order to save time, or spend time and save memory. The appropriate choice depends on which operations matter most.


Queues and Stacks

A queue and a stack are abstract data structures: they define how elements are added and removed without requiring one particular memory representation. Arrays and linked lists can serve as building blocks for implementing them.

Queues: first in, first out

A queue follows the FIFO rule: first in, first out. The earliest element added is the first one removed. A line at a store is a familiar example: people are served in the order they arrived.

The central queue operations are:

  • Enqueue: Add an element to the back of the queue.

  • Dequeue: Remove an element from the front.

Print jobs sent to a shared printer are a common example. A queue lets jobs be handled in the order they were requested.

Stacks: last in, first out

A stack follows the LIFO rule: last in, first out. The most recently added element is the first one removed. A stack of trays is an example: the tray placed on top most recently is usually the one taken first.

The central stack operations are:

  • Push: Add an element to the top of the stack.

  • Pop: Remove the top element.

An email inbox that displays the newest messages first resembles a stack in its ordering. This is useful when recent items are most important, but older items can become difficult to notice if new ones keep arriving.

Queues and stacks express different ordering policies. FIFO is useful when arrival order should be preserved; LIFO is useful when the most recently added item should be accessed first.


Dictionaries as Key–Value Structures

A dictionary is an abstract data structure that associates keys with values. A key might be a word, name, or identifier; the associated value might be a definition, page number, or other information. A hash table is one way to implement a dictionary, using a hash function to locate the bucket associated with a key.

A spelling dictionary illustrates the idea: the words are keys, and a lookup tests whether a particular word is present. A dictionary implemented with a well-designed hash table can make that membership test very fast in practice, though collisions mean the theoretical worst case may still require searching a long chain.

The key–value abstraction is more general than any one physical representation. A hash table provides one practical implementation, while the dictionary describes the operations and relationship the data structure offers.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent