C does not have a long list of built-in data structures. Its built-in types include basic types such as int, char, float and double, and derived types such as arrays, structs, unions and pointers. Most other data structures are built from these pieces. A data structure is a way of organizing data so that it can be stored, searched and changed efficiently.
Textbooks group data structures in several ways. The grouping below is one common approach.
Building blocks
- Arrays hold a fixed number of values of the same type, stored one after another in memory.
- Structs group named fields, which can have different types, into one value.
- Pointers hold memory addresses. They let one piece of data refer to another, which is how most dynamic structures are linked together.
Linear data structures
In a linear data structure, items are arranged in a single sequence.
- Arrays, described above.
- Linked lists chain nodes together. Each node stores a value and a pointer to the next node.
- Stacks add and remove items at one end, so the last item in is the first item out.
- Queues add items at one end and remove them from the other, so the first item in is the first item out.
Non-linear data structures
Items in a non-linear data structure can connect to more than one other item.
- Trees arrange nodes in a hierarchy, with a root node and child nodes below it. A binary tree allows at most two children per node.
- Graphs are nodes joined by edges, with no required hierarchy.
Hash-based data structures
- Hash tables store key-value pairs and use a hash function to find the slot for each key. This is the idea behind a dictionary in C++, such as
std::unordered_map. Standard C has no hash table, so you write one yourself or use a library.
What a linked list looks like in code
struct Node {
int value;
struct Node *next;
};
Each node holds a value and a pointer to the next node. In a typical singly linked list, the last node’s next pointer is NULL, which marks the end of the list.
For comparison, an array of five scores looks like this:
int scores[5] = {90, 85, 70, 88, 95};
Where to start
Learn arrays and structs first, since the other structures are built from them. Then try stacks and queues, which you can build with either arrays or linked nodes. Trees, graphs and hash tables come after you are comfortable with pointers. C++ offers many of these in its standard library, such as std::vector, std::list and std::map, so you can compare the hand-built versions with the library ones.