Pointers and Arrays

The elements of an array sit next to each other in memory, one after another. When you use the name of an array on its own, C++ gives you the address of its first element. So you can put it straight into a pointer, without &:

#include <iostream>
using namespace std;

int main() {
    int temps[3] = {18, 21, 25};
    int* p = temps;
    cout << (p == &temps[0]) << "\n";
    cout << *p << "\n";
    cout << *(p + 1) << "\n";
    cout << *(p + 2) << "\n";
    return 0;
}

Output:

1
18
21
25

The first line prints 1 (true): p holds the same address as &temps[0]. Reading *p gives the first element, 18.

p + 1 is the address of the next element, and p + 2 is the one after that. The * in front reads the value at that address. Doing math with addresses like this is called pointer arithmetic.

              p        p + 1    p + 2
          +--------+--------+--------+
 temps:   |   18   |   21   |   25   |
          +--------+--------+--------+

Adding 1 to a pointer moves it by one element, not by one byte. With the compiler used here, an int takes 4 bytes of memory. The compiler knows p points to ints, so p + 1 is 4 bytes further on. You only need to count in elements.

Moving the pointer

The pointer itself can also move. p++ makes it point to the next element:

int temps[3] = {18, 21, 25};
int* p = temps;
p++;
cout << *p << "\n";

Output:

21

What [ ] really does

Square brackets are a short way to write pointer arithmetic. For a pointer p, p[i] means the same as *(p + i):

int temps[3] = {18, 21, 25};
int* p = temps;
for (int i = 0; i < 3; i++) {
    cout << p[i] << " " << *(p + i) << "\n";
}

Output:

18 18
21 21
25 25

The same is true for the array name: temps[i] means *(temps + i).

This also explains why indexes start at 0. The first element is 0 steps away from the start of the array, so it is *(temps + 0).

In normal C++ code you write temps[i], because it is easier to read. Still, it helps to know what happens underneath.

In the exercise, add up the numbers in an array by reading each one through a pointer with *(p + i).