Lecture 2: Elementary Data Structures
A data structure organizes data, an ADT is the contract for using it, and in C++ you build the basics from arrays, pointers and new/delete. Most bugs here come from forgetting that raw arrays don’t know their size and that heap memory must be released exactly once.
Previous: Lecture 1 - Pointers · Next: Lecture 3 - Linked List
The slides are titled Elementary Data Structures and cover ADTs, arrays, pointers and dynamic memory. The classes and templates material (section 11) comes from the course practice sheet, not the slides.
1. Data structures, algorithms and ADTs
| Meaning | Example | |
|---|---|---|
| Data structure | how data is organized and accessed | a library shelves books by catalog |
| Algorithm | a finite series of instructions that solves a problem | look up the code, find the shelf, fetch the book |
An Abstract Data Type (ADT) defines which operations exist, not how they work inside.
flowchart TB
ADT["Stack ADT<br/>push, pop, top"] --> A["Implementation 1:<br/>array"]
ADT --> B["Implementation 2:<br/>linked nodes"]
ADT = what the operations do. Data structure = how they are implemented. The same stack ADT can sit on an array or on linked nodes.
push(3), push(7), pop() -> [3] -> [3, 7] -> [3] (popped value: 7)
Common data structures
| Structure | Key idea |
|---|---|
| Array | indexed elements |
| Linked list | nodes connected by links |
| Stack | last in, first out (LIFO) |
| Queue | first in, first out (FIFO) |
| Binary tree | hierarchical nodes |
| Graph | vertices and edges |
2. Algorithm example: find the maximum
int a[] = {4, 9, 2, 7};
int maximum = a[0];
for (int i = 1; i < 4; ++i) {
if (a[i] > maximum)
maximum = a[i];
}
// maximum = 9
Keep a running maximum and update it when a larger item appears.
| Read | max |
|---|---|
| start | 4 |
| 9 | 9 |
| 2 | 9 |
| 7 | 9 |
From problem to program
flowchart LR
U[Understand<br/>input/output] --> D[Design<br/>algorithm] --> C[Write<br/>C++] --> K[Compile,<br/>fix syntax] --> T[Run test<br/>cases] --> G[Debug logic<br/>and runtime]
A program compiles but prints 11 instead of 10. What kind of error?
A logical error. A syntax error stops compilation; wrong output from a program that builds is a logic bug.
3. Static vs dynamic memory
| Fixed-size (static array) | Dynamically allocated | |
|---|---|---|
| Size | fixed at compile time | chosen at runtime |
| Example | int scores[5]; |
int* p = new int[n]; |
| Cleanup | automatic (local arrays have automatic storage) | you must release it |
flowchart LR
subgraph Stack["Stack (automatic)"]
s["int scores[5]<br/>freed at end of scope"]
end
subgraph Heap["Heap (free store)"]
h["new int[n]<br/>lives until delete[]"]
end
A local variable dies when its scope ends. A new object lives until you delete it, even after the pointer that found it is gone.
4. Static arrays
int scores[5] = {11, 22, 33, 44, 55};
std::cout << scores[2]; // 33
scores[1] = 99; // update element 1
- First element is index
0. For sizen, valid indices are0ton - 1. - All elements have the same type.
- C++ does not check bounds.
scores[5]is undefined behaviour, not an error message.
What does this print?
int a[4] = {5, 8, 3, 1};
a[2] = a[0] + a[1];
std::cout << a[2];
Answer: 13. Index 2 is overwritten with 5 + 8.
5. Arrays as function parameters
int findMax(const int a[], int n) {
int best = a[0];
for (int i = 1; i < n; ++i)
if (a[i] > best) best = a[i];
return best;
}
const int a[] is adjusted to const int* a. The function cannot know the length, so pass it separately (n). sizeof(a) inside the function gives the pointer size, not the array size.
constforbids changing elements through that parameter (a[0] = 1;fails to compile). Reading is fine.
6. Two-dimensional arrays
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
std::cout << matrix[1][2]; // 6 (row 1, column 2)
Index order is [row][column], both from zero. Storage is row-major: row 0’s elements, then row 1’s.
As a parameter, the column count is required
const int COLS = 3;
void display(const int a[][COLS], int rows) {
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < COLS; ++c)
std::cout << a[r][c] << " ";
std::cout << "\n";
}
}
To find a[r][c] the compiler computes r * COLS + c, so it needs COLS. The row count is passed separately.
Declaration for a[2][3] |
Valid? |
|---|---|
void f(int a[][3]) |
yes |
void f(int a[2][]) |
no, column missing |
void f(int a[][]) |
no |
7. Value, address and pointers (recap)
int x = 45;
std::cout << x; // value: 45
std::cout << &x; // address of x (varies per run)
int* p = &x;
std::cout << *p; // 45
*p = 20; // x is now 20
| Expression | Meaning |
|---|---|
x |
the stored value |
&x |
where it lives |
p |
holds &x |
*p |
the object p points to |
* has two rolesint* p; declares a pointer. *p = 20; dereferences it. Never dereference a pointer until it points to a valid object. See Lecture 1 - Pointers.
Trace it
int a = 4;
int* p = &a;
*p = *p + 3;
std::cout << a;
Answer: 7. Writing through p changes a itself.
8. The heap: new and delete
int* p = new int; // allocate one int
*p = 15;
std::cout << *p; // 15
delete p; // release
p = nullptr; // clear the pointer
new int(8) allocates and initializes. new returns an address, and the caller owns it.
delete- The old address is invalid: never read
*p(use-after-free). - Never delete the same allocation twice (double delete).
- Setting
p = nullptrmakes a laterdelete p;harmless andp != nullptrtestable. Both mistakes are undefined behaviour.
Debug this
int* h = new int(9);
int* z = new int(5);
*z = *h + *z;
delete z;
std::cout << *z; // BUG: use after delete
delete h;
Fix: print *z (it is 14) before delete z;.
9. Dynamic arrays
int n = 4;
int* a = new int[n]{2, 4, 6, 8};
for (int i = 0; i < n; ++i)
std::cout << a[i] << " ";
delete[] a;
a = nullptr;
| Allocation | Release |
|---|---|
new T |
delete |
new T[n] |
delete[] |
delete p; on an array from new[] is undefined behaviour. The array form must also be freed with the array form.
A raw dynamic array picks its size at runtime, but it still can’t grow in place.
10. Resizing: allocate, copy, delete, repoint
flowchart LR
A["1. Allocate<br/>larger block"] --> B["2. Copy<br/>old elements"] --> C["3. delete[]<br/>old block"] --> D["4. Point at<br/>new block"]
void extendArray(int*& a, int& size) {
int newSize = size * 2;
int* b = new int[newSize]{};
for (int i = 0; i < size; ++i)
b[i] = a[i];
delete[] a;
a = b;
size = newSize;
}
int*&?The function must replace the caller’s pointer. A plain int* a would be a copy, so a = b would only change the local copy and the caller would keep a deleted pointer. size is a reference so the caller sees the new capacity too.
Order matters: copy before delete[], or the data is gone.
Growing from empty, and size vs capacity
size is how many elements are in use. capacity is how many fit. A grow that also handles an empty array:
void grow(int*& data, int size, int& capacity) {
int next = capacity == 0 ? 1 : capacity * 2;
int* larger = new int[next];
for (int i = 0; i < size; ++i) // copy only the used elements
larger[i] = data[i];
delete[] data; // deleting nullptr is safe
data = larger;
capacity = next;
}
Full array {8, 1, 6} (size 3, capacity 3) grows to capacity 6. Appending 4 gives size 4, capacity 6, elements {8, 1, 6, 4}.
Stale aliases after a resize
int* a = new int[4]{2, 4, 6, 8};
int* middle = a + 2; // alias into the OLD block
shrink(a); // old block is deleted, a now points to a new one
// *middle -> dangling: undefined behaviour
middle = a + 2; // refresh the alias from the new block
std::cout << *middle; // 6
delete[] a;
A corrected shrink copies only the first three values (i < 3, not i <= 3) and releases with delete[], not delete:
void shrink(int*& a) {
int* smaller = new int[3];
for (int i = 0; i < 3; ++i)
smaller[i] = a[i];
delete[] a;
a = smaller;
}
delete[] invalidates every pointer into the old array, not just a. Recompute aliases like middle from the new block, or use indices, which survive a resize.
std::vector<int> does all of this (growth, copying, cleanup) for you, so prefer it unless you are practicing the mechanics.
11. Classes and templates (practice sheet)
A class bundles data with the operations that keep it valid. The data is private, and the public functions are the interface (the ADT idea from section 1).
class ScoreLog {
int scores[4]; // private: callers can't touch these
int count = 0;
public:
bool add(int score) {
if (count == 4) return false; // full: nothing changes
scores[count++] = score;
return true;
}
bool removeLast(int& removed) {
if (count == 0) return false; // empty: `removed` untouched
removed = scores[--count];
return true;
}
};
- A failed operation returns
falseand leaves the object and any output argument unchanged. removedis a reference so the function can hand a value back.
Trace: adds of 6, 3, 8, 5, 9 return true, true, true, true, false and leave [6, 3, 8, 5]. Two removals return true and give 5, then 8. Adding 7 returns true and leaves [6, 3, 7].
Class templates
template <typename T>
class Pair {
T first, second;
public:
Pair(T a, T b) : first(a), second(b) {}
T larger() const { return first < second ? second : first; }
void swapValues() {
T saved = first;
first = second;
second = saved;
}
};
larger() constdoesn’t modify the object, so it is markedconst.- Using
first < second ? second : firstreturns the first value when they are equal. Pair<int>(8, 3)becomes(3, 8)afterswapValues();larger()is8both times.Pair<double>(2.5, 4.75)becomes(4.75, 2.5);larger()is4.75both times.
Row sums with a 2D array parameter
int bestRow(const int a[][3], int rows) {
int best = -1;
long long bestSum = 0;
for (int i = 0; i < rows; ++i) {
long long sum = static_cast<long long>(a[i][0]) + a[i][1] + a[i][2];
if (best == -1 || sum > bestSum) { best = i; bestSum = sum; }
}
return best;
}
The strict > keeps the first row on ties, and -1 means no rows. For {{-2,4,1},{5,-4,2},{0,1,1}} the sums are 3, 3, 2, so it returns 0.
Quick self-test
What does &x return?
The address of x.
How is *p different from p?
p is the address stored in the pointer. *p is the object at that address.
Why must new[] match delete[]?
They are two forms of allocation/release; using the single-object delete on an array is undefined behaviour.
Why does a 2D array parameter need its column size?
The compiler needs the column width to compute each element’s offset in row-major memory.
What are the three steps of resizing?
Allocate larger storage, copy the elements, delete the old block (then point at the new one).
When should you prefer std::vector?
Almost always, whenever you need a growable array. It manages memory automatically.
Cheat sheet
- ADT = contract (operations); data structure = implementation.
- Array indices run
0ton - 1; no bounds checking. - Array parameters become pointers: pass the length, use
constto read only. - 2D array parameters need the column count.
&gets an address,*dereferences.new/deletefor one object,new[]/delete[]for arrays.- Never use memory after
delete, neverdeletetwice; set tonullptrafter. - Resize = allocate bigger, copy, delete old, repoint (
int*&to update the caller). - A resize invalidates every pointer into the old block: refresh aliases or use indices.
- Class: private data, public operations; failed operations leave state unchanged.
- Template:
template <typename T>makes one class per type; mark non-mutating membersconst.