All lessons

8. Pointers

Pointers and arrays

0 of 5 activities0%

Reading 1

Arrays decay to pointers

Open

The name of an array can be used as a pointer to its first element. a[i] is equivalent to *(a + i).

Pointer arithmetic moves by elements, not raw bytes: p + 1 points to the next int if p is an int*.

Prefer clear indexing while learning; knowing the pointer view helps when reading other people’s code and when functions take arrays.

int a[3] = {10, 20, 30};
int* p = a;        // points at a[0]
cout << *p << endl;
cout << *(p + 1) << endl;  // 20
cout << p[2] << endl;      // 30

Check 2

Equivalence

Open

Which expression equals a[2]?

Fill in 3

First element

Open

If p points to the first element of an array, *p is the same as

Try it 4

Walk with a pointer

Open

Trace p through the array.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Second element via pointer

Open

Read three integers into an array a[3]. Using a pointer p set to a, print the second element (index 1) via the pointer.

main.cpp
Loading editor…