Kodewick
Start learning →
Arrays and vector: straight to an index6 / 52

Arrays and vector: straight to an index

Lesson 6 of 52 · Part 2 · Arrays and linked lists · about 18 minutes

A C++ array or vector stores its elements one after another, so the address of a[i] is the start plus i elements, one step away; v[i] doesn't check the bounds, while v.at(i) throws an exception.

a[0] or a[999999]: which is faster to get? Neither. This lesson shows why: a C++ array is one block of memory, one element after another, so where element i is can be worked out, not searched for. A vector is laid out the same way, so v[i] is one step too.

One after another

int a[5] = {10, 20, 30, 40, 50}; is five ints side by side in memory. An int takes 4 bytes, so each next one is 4 further on.

stack

0x1000a[0]int10
0x1004a[1]int20
0x1008a[2]int30
0x100ca[3]int40
0x1010a[4]int50
int a[5]: five ints side by side, 4 bytes each

(The addresses are an example: the real ones may change every run, but "4 apart" doesn't.)

Choose one

In int a[5], a[0] is at address 2000, and an int takes 4 bytes. Where is a[1]?

Guess the outputA wrong guess is fine

sizeof measures how many bytes something takes. What does this program print?

1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    cout << sizeof(a) << "\n";7    return 0;8}

Working out the address

The elements sit side by side and are all the same size, so you never have to search for element i. Its address is simply:

address of a[i] = address of a + i × the size of one element

One multiplication and one addition, whatever i is and however long the array: getting an element by index is O(1). It is also why indexes start at 0: the first element is 0 elements from the start.

We don't print the addresses themselves (they change between runs), only how far apart they are. Cast to char* and subtract, and you get bytes; subtract directly, and you get elements:

main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    // how many bytes apart two addresses are7    cout << "a[1] is " << (char*)&a[1] - (char*)&a[0] << " bytes after a[0]\n";8    cout << "a[3] is " << (char*)&a[3] - (char*)&a[0] << " bytes after a[0]\n";9    cout << "an int takes " << sizeof(int) << " bytes\n";10    // without char*: how many elements apart11    cout << "&a[3] - &a[0] = " << &a[3] - &a[0] << "\n";12    return 0;13}
Output
a[1] is 4 bytes after a[0]
a[3] is 12 bytes after a[0]
an int takes 4 bytes
&a[3] - &a[0] = 3
Guess the outputA wrong guess is fine

A double takes 8 bytes. How many bytes after &d[0] is &d[4]?

1#include <iostream>2using namespace std;3 4int main() {5    double d[10];6    cout << (char*)&d[4] - (char*)&d[0] << "\n";7    return 0;8}

Pointers work it out the same way

a[i] is really *(a + i): used as a pointer, an array's name is the address of its first element, and + i multiplies by the element's size for you.

main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    int* p = a;          // points at a[0]7    cout << a[3] << " " << *(p + 3) << "\n";8    p = p + 2;           // two ints further on9    cout << *p << " " << p[1] << "\n";10    return 0;11}
Output
40 40
30 40

p[1] is *(p + 1): one further on from where p points, which is 40.

Guess the outputA wrong guess is fine

p points at a[1]. What does this program print?

1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    int* p = a + 1;7    cout << *p << " " << p[2] << "\n";8    return 0;9}
Fill inTap one to fill a blank; tap a blank to take it back

Fill in a number so the program prints 30.

1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    cout << *(a + ) << "\n";7    return 0;8}
Exercise 1

Print it backwards

Using *(a + i), print the array backwards, from the last element to the first.

It should print
50 40 30 20 10
exercise1.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    // i goes from 4 down to 0, print *(a + i)7    cout << "\n";8    return 0;9}
Output
Press Run or Ctrl+Enter

2-D arrays: one row after another

int m[2][3] is a table of 2 rows and 3 columns. But memory has no rows or columns, just one long strip, so C++ lays the table out row after row: first the 3 values of row 0, then straight after them the 3 of row 1. This is called row-major order.

stack

0x1000m[0][0]int1
0x1004m[0][1]int2
0x1008m[0][2]int3
0x100cm[1][0]int4
0x1010m[1][1]int5
0x1014m[1][2]int6
int m[2][3] = {{1, 2, 3}, {4, 5, 6}}: row 0’s three values, then row 1’s, six ints in one strip

So to reach m[i][j], skip i whole rows (3 values each), then j more:

address of m[i][j] = start + (i × number of columns + j) × element size

Just like a 1-D array, it is one calculation away: still O(1). Exams love this one. Watch out: you multiply by the number of columns.

main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};6    cout << (char*)&m[1][0] - (char*)&m[0][0] << "\n";7    cout << (char*)&m[1][2] - (char*)&m[0][0] << "\n";8    return 0;9}
Output
12
20

m[1][0] has 1 × 3 + 0 = 3 ints before it, so it is 12 bytes on; m[1][2] has 1 × 3 + 2 = 5 before it, so 20 bytes on.

Guess the outputA wrong guess is fine

int m[3][4] has 3 rows and 4 columns; an int takes 4 bytes. How many bytes after &m[0][0] is &m[2][1]?

1#include <iostream>2using namespace std;3 4int main() {5    int m[3][4];6    cout << (char*)&m[2][1] - (char*)&m[0][0] << "\n";7    return 0;8}
Choose one

int m[4][5] is stored row by row from address 1000, and an int takes 4 bytes. What is the address of m[3][2]?

Past the end: nobody stops you

int a[5] has a[0] to a[4]. Write a[5] and the address still works out, but that memory isn't the array's: reading it gets something else, and writing it breaks another variable. C++ arrays don't check indexes, and neither does a vector's v[i].

stack

0x100ca[3]int40
0x1010a[4]int50
0x1014sumint150

Writing one past the end (a sketch: how variables are laid out is up to the compiler): the address of a[5] lands right on sum
main.cpp
1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    int sum = 0;7    for (int i = 0; i <= 5; i++)   // one step too far8        sum += a[i];9    cout << sum << "\n";10    return 0;11}
Output
index 5 out of bounds for type 'int [5]'

What happened: Stopped at line 8. This goes past the end of a vector, an array or a string. Real C++ would read or overwrite whatever is next in memory.

Press Run and see what happens. Our C++ stops right there and says which element was out of bounds; real g++ doesn't stop and works out some unpredictable number. The usual mistake is i <= n; it should be i < n.

Choose one

int a[5]; Which of these loops goes past the end?

Change it

This loop goes one step too far. Change only the number in the green box so it adds exactly the 5 elements and prints 150.

1#include <iostream>2using namespace std;3 4int main() {5    int a[5] = {10, 20, 30, 40, 50};6    int sum = 0;7    for (int i = 0; i <= ; i++)8        sum += a[i];9    cout << sum << "\n";10    return 0;11}
Should print
150
Exercise 2

Add them up

Finish the loop: add up the 6 numbers in v by index.

It should print
30
exercise2.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> v = {3, 8, 1, 9, 4, 5};7    int sum = 0;8    // i goes from 0 to v.size() - 19    cout << sum << "\n";10    return 0;11}
Output
Press Run or Ctrl+Enter

With the STL

A fixed array's size is set when you write the program. vector<int> is the standard library's array: its elements are also in one contiguous block (on the heap), its size can be chosen while the program runs, and it knows how many it holds (v.size()). So v[i], like a[i], is one address calculation: O(1).

What it adds is v.at(i): it checks i < v.size() first and throws an out_of_range exception when it isn't, instead of quietly reading something else.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> v = {10, 20, 30, 40, 50};7    cout << "size = " << v.size() << "\n";8    cout << v[3] << " " << v.at(3) << "\n";9    cout << "&v[3] - &v[0] = " << &v[3] - &v[0] << "\n";   // one after another too10    vector<int> zeros(6);           // size chosen at run time: six 0s11    zeros[2] = 7;12    for (int x : zeros)13        cout << x << " ";14    cout << "\n";15    try {16        cout << v.at(5) << "\n";    // checks the index: throws when it is out of range17    } catch (...) {18        cout << "at(5) is out of range: v only has 0 to " << v.size() - 1 << "\n";19    }20    return 0;21}
Output
size = 5
40 40
&v[3] - &v[0] = 3
0 0 7 0 0 0 
at(5) is out of range: v only has 0 to 4
fixed array int a[5]vector<int> v
memoryone block (on the stack for a local)one block, on the heap
sizeset when you write the programset at run time, and can change (next two lessons)
how manyyou keep trackv.size()
[i]O(1), no checkO(1), no check
bounds checknonev.at(i), throws out_of_range

vector<int> zeros(6) with round brackets is 6 elements, all 0; vector<int> v = {10, 20} with braces is just those two elements.

In interviews: "Why is indexing an array O(1)": contiguous memory, address = start + i × element size, one calculation. A vector's elements are contiguous too, so v[i] is also O(1), and &v[0] can be used as a plain array pointer. The follow-up on [] vs at(): [] doesn't check (fast), at() checks and throws.

Guess the outputA wrong guess is fine

Round brackets and curly braces make different vectors. What does it print?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> v(4);7    v[1] = 5;8    vector<int> w = {4};9    cout << v.size() << " " << v[1] + v[2] << " " << w.size() << "\n";10    return 0;11}

Summary

Take-away

Arrays and vector: one contiguous block, indexing is O(1)

  • address of a[i] = start + i × element size
  • a[i] is *(a + i); indexes start at 0
  • arrays and v[i] don't check bounds: loop with i < n
  • a vector is contiguous too; v.at(i) checks and throws when out of range
  • address of m[i][j] = start + (i × columns + j) × element size
1int a[5];2a[i]          // element i, its address in one step3*(a + i)      // the same thing4vector<int> v(n);   // n zeros5for (int i = 0; i < n; i++)   // not i <= n