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

Speaker 1Speaker 2

C Data Structures and Pointers

13:51
0:00-13:51
  1. Maria

    Today we’re building up from pointers to some of the data structures that make programs more powerful. The key idea is that a data structure is a way to arrange information in memory. And the trade-off we’ll keep seeing is that a choice that saves time may use more memory, or a choice that makes memory flexible may make searching slower.

  2. Corey

    Let’s begin with the pointer basics. If I declare `int *x` and `int *y`, I’ve created two variables that can hold addresses of integers. But that alone doesn’t give either pointer a valid integer to point to.

  3. Maria

    Exactly. If I write `x = malloc(sizeof(int))`, I’m asking for enough memory to store an integer, and `malloc` returns the address of that memory. Then `*x = 42` means: follow the address in `x` and store 42 there. The star in that expression is the dereference operator.

  4. Corey

    And the dangerous version is trying to do `*y = 13` before giving `y` a valid address. An uninitialized pointer could contain a garbage address, so using it can cause a memory error, such as a segmentation fault.

  5. Maria

    There’s another important distinction: allocating a pointer and allocating the thing it points to are separate steps. If I assign `y = x`, now both pointers hold the same address. They share the same integer, so changing it through `y` changes what you see through `x` too.

  6. Corey

    Which means assigning one pointer to another doesn’t create a new integer. It just copies the address. If `*x` was 42 and then I set `*y` to 13, the shared integer is now 13.

  7. Maria

    That pointer idea matters when we revisit arrays. An array has a fixed size, so if you start with room for three integers and want a fourth, you can’t count on the memory immediately after the array being available. Other data may be occupying it.

  8. Corey

    So one approach is to allocate a larger block somewhere else, copy the old values into it, add the new value, and free the old block. Copying three values is a few steps, but in general copying an array of n values takes time proportional to n. That’s linear time, or Big O of n.

  9. Maria

    That’s the cost of growing an array this way. The payoff is that arrays let you jump straight to an index, like element 0, 1, or 2. That’s constant-time access, often called random access. And if the array is sorted, that access lets binary search find a value in logarithmic time.

  10. Corey

    In C, we can allocate a block dynamically with `malloc`. For example, `malloc(3 * sizeof(int))` requests enough memory for three integers. We can store the returned address in an `int *`, then use square brackets just as we would with an array.

  11. Maria

    The pointer and the array aren’t identical in every detail, but in this use they both refer to a contiguous chunk of memory. Square-bracket notation steps by elements, not by single bytes: if an integer takes four bytes, index 1 is four bytes after index 0, and index 2 is eight bytes after it.

  12. Corey

    And good practice says to check whether `malloc` returned `NULL`, which indicates that the allocation failed. When you’re finished with a dynamically allocated block, call `free` on its address so the computer can reclaim that memory.

  13. Maria

    If you need to grow or shrink an existing block, C also provides `realloc`. It can resize the block and handle moving the existing contents if needed. You still need to check for failure and keep track of the resulting address.

  14. Corey

    That temporary address matters. If you overwrite your only pointer to the old allocation before keeping track of the new one, you can lose track of memory you asked for. And when the program is done with the resized block, that block still needs to be freed.

  15. Maria

    So the big array lesson is a trade-off: fast indexing and the possibility of binary search, but resizing can involve copying values. A linked list offers another way to arrange data—one that doesn’t require all the values to sit next to each other in memory.

  16. Corey

    A linked list is built from nodes. Each node in our example holds an integer and a pointer to the next node. The nodes can live in different parts of memory; the pointers connect them into a list.

  17. Maria

    In C, we can describe a node with a structure containing an `int number` and a `next` pointer. Since `next` points to another node, the structure needs to refer to itself. One common form is `typedef struct node { int number; struct node *next; } node;`.

  18. Corey

    The longer name, `struct node`, is needed inside the definition because the shorter alias, `node`, isn’t available until the typedef is complete. And because a pointer can refer to a node that doesn’t exist, the end of the list is marked with `NULL`.

  19. Maria

    An empty list can be represented by a pointer called `list` that is initialized to `NULL`. To add a value, allocate enough memory for an entire node with something like `malloc(sizeof(node))`, check that it didn’t return `NULL`, and then fill in the node’s fields.

  20. Corey

    When a pointer such as `n` points to a node, `n->number` accesses that node’s number field, and `n->next` accesses its next pointer. That arrow notation is a convenient shorthand for dereferencing the pointer and then using dot notation.

  21. Maria

    If the new node is the first one, the list pointer needs to point to it. If it’s going at the end, you have to follow the existing next pointers until you reach a node whose `next` is `NULL`, then connect that node to the new one.

  22. Corey

    That’s why a temporary pointer is useful: it lets you walk through the list without losing the pointer to its beginning. You keep following `next` until there’s no next node. To print the list, you can use the same traversal and print each node’s number.

  23. Maria

    Insertion at the beginning needs a careful order. First make the new node point to the node that was previously first. Then update the list pointer to point to the new node. If you point the list at the new node first, you can lose your path to every old node.

  24. Corey

    That lost path is a memory leak: the program can no longer reach the old nodes to use or free them. Inserting in the middle has a similar pointer-order issue. Make the new node point to the following node first, then update the previous node to point to the new one.

  25. Maria

    Linked lists make it possible to add nodes without copying all the existing values into a bigger, contiguous block. But if you want to insert a value in sorted order, you still have to walk through the list to find the right spot.

  26. Corey

    That gives us the central trade-off. A linked list can grow dynamically, but it loses random access: you can’t jump straight to the middle node. You have to follow pointers from the beginning, so searching a sorted linked list takes linear time rather than the logarithmic time binary search can achieve with an array.

  27. Maria

    And adding to the end, or inserting in sorted order, can also take linear time because you may need to traverse the list. Adding at the beginning is the exception: once you have the new node, that pointer update can be done in constant time.

  28. Corey

    Now we can combine the useful idea of linked nodes with the direction choices of binary search. Imagine each node has two pointers instead of one: `left` and `right`. Arrange the values so that everything left of a node is smaller, and everything right of it is larger.

  29. Maria

    That structure is a binary search tree. It’s binary because each node has at most two children, and it’s a search tree because the values are arranged according to that left-smaller, right-larger rule. The rule applies recursively to every node and its subtrees.

  30. Corey

    To look for a value, start at the root, the top node. Compare the target with that node’s value. If the target is smaller, follow the left pointer; if it’s larger, follow the right pointer. If the pointer you need is `NULL`, the value isn’t there.

  31. Maria

    That’s binary search expressed through pointers. In a balanced tree, the number of steps grows logarithmically with the number of values. But keeping a tree balanced matters: if you keep adding values in a way that makes it very lopsided, the tree can become tall and searching can lose that advantage.

  32. Corey

    A balanced binary search tree can also support insertion in logarithmic time, while still growing without copying the entire collection into a new array. The pointers let the structure connect nodes wherever they happen to be in memory.

  33. Maria

    The next structure aims for something even faster: a hash table. Think of an array of buckets, with a rule—called a hash function—that takes an input, such as a name, and tells us which bucket to use.

  34. Corey

    For name tags, a simple hash function might look at the first letter. Then a name beginning with A goes into the A bucket, and a name beginning with Z goes into the Z bucket. Because the buckets are in an array, you can jump directly to one.

  35. Maria

    But two names can start with the same letter. That’s a collision: two inputs want the same bucket. One way to handle it is to make each bucket the beginning of a linked list. Then names that collide are connected in that bucket.

  36. Corey

    A hash table is therefore an array combined with linked lists. If the hash function distributes names well, looking up a name can be very fast. But if many names land in the same bucket, you have to walk through that bucket’s list, and in the worst case searching can take linear time.

  37. Maria

    You could try hashing on more letters to reduce collisions, but that can require many more buckets. With two letters, there are 26 times 26 possible combinations; with three, there are even more. So a hash table involves a time-and-space trade-off, and no simple choice guarantees that collisions disappear.

  38. Corey

    In practice, a good hash function can make a hash table much faster on average than searching one long list. But the theoretical worst case remains linear if the inputs all collide. If every item had its own bucket, lookup would be constant time, but creating enough space and finding a suitable hashing rule are part of the challenge.

  39. Maria

    A trie offers another way to search words and names. The name comes from retrieval, and the structure is a tree whose nodes are arrays. To store a word, follow one array entry for each character, creating a new array node along the path when needed.

  40. Corey

    For example, storing Hagrid follows H, then A, then G, then R, then I, then D. A word can be marked as ending at its final character. Names with shared beginnings reuse the same initial path, so Hagrid, Harry, and Hermione all share the H branch.

  41. Maria

    To find a name, follow the entries for its letters. The work depends on the length of the name, not on how many other names are stored in the trie. Since names have a bounded length, that lookup is treated as constant time with respect to the number of stored names.

  42. Corey

    The price is memory. Each node is an array with many possible character entries, even if only a few are used. A trie can make searching especially fast, but it may use substantially more memory than a more compact structure.

  43. Maria

    These structures can also serve as building blocks for abstract data structures. A queue represents a line and follows FIFO: first in, first out. Its main operations are enqueue, joining the line, and dequeue, leaving the line.

  44. Corey

    That ordering matters for things like food orders or shared printers. If requests are handled fairly, the first order or print job submitted should be the first one served. A queue can be implemented using structures such as arrays or linked lists.

  45. Maria

    A stack follows the opposite rule, LIFO: last in, first out. Think of a pile of trays—you take the top one, which is the one most recently placed there. The operations are called push, to add an item, and pop, to remove the top item.

  46. Corey

    An inbox that puts the newest emails at the top behaves like a stack in that sense. That can make recent messages easy to see, though older messages can be pushed farther down. The right structure depends on what order the situation calls for.

  47. Maria

    A dictionary is another abstraction: it maps keys to values. A word can be the key and information associated with that word the value. A hash table can be used to implement a dictionary, providing a way to look up the value associated with a key.

  48. Corey

    That’s useful for spell-checking: store a large collection of correctly spelled words, then check whether each word in a document is present. A hash table can make those checks much faster in practice, which is why implementing one is a useful programming exercise.

  49. Maria

    So the episode’s big picture is that there isn’t one best structure for every job. Arrays give fast indexing but can be costly to resize. Linked lists grow flexibly but require traversal. Trees can restore fast searching when balanced, while hash tables and tries offer other ways to speed up lookups, each with its own memory and design trade-offs.

  50. Corey

    And queues, stacks, and dictionaries show how those building blocks support useful behaviors: first in, first out; last in, first out; and key-to-value lookup. Choosing a data structure means asking what matters most for the problem—access, insertion, ordering, or memory—and accepting the trade-offs that come with it.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent