Kodewick
Start learning →
Arrays: straight to any index4 / 50

Arrays: straight to any index

Lesson 4 of 50 · Part 2 · Arrays and linked lists · about 12 minutes

A C array is one block of memory with the elements side by side, so the address of a[i] is the start plus i elements and reading any element is O(1); indexes start at 0, and C never checks the bounds.

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.

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 <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    printf("%d\n", (int)sizeof(a));6    return 0;7}

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:

main.c
1#include <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    // how many bytes apart two addresses are6    printf("a[1] is %d bytes after a[0]\n", (int)((char *)&a[1] - (char *)&a[0]));7    printf("a[3] is %d bytes after a[0]\n", (int)((char *)&a[3] - (char *)&a[0]));8    printf("an int takes %d bytes\n", (int)sizeof(int));9    return 0;10}
Output
a[1] is 4 bytes after a[0]
a[3] is 12 bytes after a[0]
an int takes 4 bytes
Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3int main(void) {4    double d[10];5    printf("%d\n", (int)((char *)&d[4] - (char *)&d[0]));6    return 0;7}
Choose one

short s[10]; A short takes 2 bytes, and s starts at address 1000. What is the address of s[6]?

Pointers work it out the same way

In C, 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.c
1#include <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    int *p = a;          // points at a[0]6    printf("%d %d\n", a[3], *(p + 3));7    p = p + 2;           // two ints further on8    printf("%d\n", *p);9    return 0;10}
Output
40 40
30
Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    int *p = a + 1;6    printf("%d %d\n", *p, p[2]);7    return 0;8}
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 <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    printf("%d\n", *(a + ));6    return 0;7}
Exercise 1

Backwards

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

It should print
50 40 30 20 10
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    // i from 4 down to 0, print *(a + i)6    printf("\n");7    return 0;8}
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.c
1#include <stdio.h>2 3int main(void) {4    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};5    printf("%d\n", (int)((char *)&m[1][0] - (char *)&m[0][0]));6    printf("%d\n", (int)((char *)&m[1][2] - (char *)&m[0][0]));7    return 0;8}
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 <stdio.h>2 3int main(void) {4    int m[3][4];5    printf("%d\n", (int)((char *)&m[2][1] - (char *)&m[0][0]));6    return 0;7}
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: C won't stop 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 itself doesn't check indexes.

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.c
1#include <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    int sum = 0;6    for (int i = 0; i <= 5; i++)   // one step too far7        sum += a[i];8    printf("%d\n", sum);9    return 0;10}
Output
index 5 out of bounds for type 'int [5]'

What happened: Stopped at line 7. This goes past the end of 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 gcc 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 <stdio.h>2 3int main(void) {4    int a[5] = {10, 20, 30, 40, 50};5    int sum = 0;6    for (int i = 0; i <= ; i++)7        sum += a[i];8    printf("%d\n", sum);9    return 0;10}
Should print
150
Exercise 2

Add them up

Finish the loop to add up the 6 numbers in the array.

It should print
30
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int a[6] = {3, 8, 1, 9, 4, 5};5    int sum = 0;6    // from index 0 to 57    printf("%d\n", sum);8    return 0;9}
Output
Press Run or Ctrl+Enter

Summary

Take-away

An array is one block of memory: indexing is O(1)

  • address of a[i] = start + i × element size
  • a[i] is *(a + i); indexes start at 0
  • C doesn't check the bounds: loop with i < n
1int a[5];2a[i]          // element i: its address in one step3*(a + i)      // the same thing4for (i = 0; i < n; i++)   // not i <= n