Lecture 2: Elementary Data Structures

One-line version

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

About the title

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"]
What vs how

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
Storage duration is not scope

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 size n, valid indices are 0 to n - 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;
}
The array decays to a pointer

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.

Pass by value, but the value is a pointer

The array is never copied. Its name decays to a pointer to the first element, and that pointer is passed by value.

  • The elements are shared with the caller: without const, a[0] = 99; changes the caller’s array.
  • The pointer itself is a local copy: a = other; inside the function does not affect the caller.
void setFirst(int a[]) { a[0] = 99; }   // same as int* a

int x[3] = {1, 2, 3};
setFirst(x);      // x[0] is now 99
  • const forbids changing any element through that parameter, not just the first one: a[i] = x; fails to compile for any 0 <= i < n. 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 roles

int* 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.

After delete
  • The old address is invalid: never read *p (use-after-free).
  • Never delete the same allocation twice (double delete).
  • Setting p = nullptr makes a later delete p; harmless and p != nullptr testable. 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[]
Always match them

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;
}
Why 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 pointers after a resize

The whole idea

A resize moves the data to a new address. Any pointer that saved the old address now points at freed memory.

Step 1: two pointers can share one block. A pointer stores only an address. Copying a pointer gives you a second pointer to the same memory. The data is not copied.

int* p = new int[3]{1, 2, 3};
int* q = p;        // q holds the same address as p
delete[] p;        // frees the block itself
// q[0]            // undefined behaviour: q still holds the address, but the block is gone

delete[] p frees the block, not “p’s copy” of it, so q breaks too. C++ does not find and fix the other pointers for you.

Step 2: every resize contains that delete[]. extendArray, grow and shrink all follow the same pattern: allocate a new block, copy, delete[] the old block, and point a at the new one. Here is shrink:

void shrink(int*& a) {
    int* smaller = new int[3];
    for (int i = 0; i < 3; ++i)   // i < 3, not i <= 3
        smaller[i] = a[i];
    delete[] a;                   // delete[], not delete
    a = smaller;
}

Because a is an int*&, the caller’s a gets the new address. No other pointer does.

Step 3: the trap.

int* a = new int[4]{2, 4, 6, 8};
int* middle = a + 2;   // the address of the 6 in the OLD block
shrink(a);
// *middle             // undefined behaviour
Before shrink(a) After shrink(a)
a old block {2, 4, 6, 8} new block {2, 4, 6}
middle the 6 in the old block still the old address, now freed
*middle 6 undefined behaviour

This is the same situation as q in step 1. middle is just another pointer into the old block.

Step 4: the fix. Either recompute the pointer from the new block after the resize:

shrink(a);              // a now points to the new block
middle = a + 2;         // recompute from the new a
std::cout << *middle;   // 6

or keep an index instead of a pointer. An index is a position rather than an address, so it is still valid after the move:

int* a = new int[4]{2, 4, 6, 8};
int mid = 2;              // a position, not an address
shrink(a);
std::cout << a[mid];      // 6: a[mid] is computed from the NEW a
delete[] a;
Rule

After any resize, treat every pointer you saved into the old array as dead. Recompute it from the new a, or store an index.

In practice

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 false and leaves the object and any output argument unchanged.
  • removed is 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() const doesn’t modify the object, so it is marked const.
  • Using first < second ? second : first returns the first value when they are equal.
  • Pair<int>(8, 3) becomes (3, 8) after swapValues(); larger() is 8 both times. Pair<double>(2.5, 4.75) becomes (4.75, 2.5); larger() is 4.75 both 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 0 to n - 1; no bounds checking.
  • Array parameters become pointers: pass the length, use const to read only.
  • 2D array parameters need the column count.
  • & gets an address, * dereferences.
  • new / delete for one object, new[] / delete[] for arrays.
  • Never use memory after delete, never delete twice; set to nullptr after.
  • 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 members const.