Course outline · 0% complete

0/27 lessons0%

Course overview →

Arrays, Pointer Arithmetic, and References vs Pointers

lesson 5-2 · ~12 min · 14/27

Raw arrays are how memory actually stores sequences: elements at consecutive addresses, nothing else. std::vector, std::string, and every cache-friendly structure you will ever use are built on exactly this layout, and interviewers probe it to check you know what your abstractions cost underneath.

C arrays and pointer arithmetic

A raw C array is a fixed-length block of elements sitting side by side in memory:

int a[4] = {10, 20, 30, 40};

The array's name converts to a pointer to its first element, and adding to a pointer moves it forward by whole elements (the compiler multiplies by the element size for you):

int* p = a;        // points at a[0]
std::cout << *p;        // 10
std::cout << *(p + 2);  // 30, two ints further along
p++;                    // now points at a[1]

In fact a[i] is defined as *(a + i). Indexing is pointer arithmetic. There is no bounds checking: a[100] compiles and reads whatever bytes happen to be there. Undefined behavior again.

You will mostly use std::vector (unit 8) instead of raw arrays, but interviews and real codebases expect you to understand this layer.

10203040a[0]a[1]a[2]a[3]p
p++ steps the pointer one whole element to the right. The elements of an array sit contiguously in memory, which is what makes this walk possible.

Code exercise · cpp

Run this pointer walk over an array. Each loop iteration dereferences p and then advances it one element.

Code exercise · cpp

Your turn: sum the array by walking a pointer across it — no indexing allowed. The loop is written; fill in the body so it prints 30.

References vs pointers, the final scorecard

A reference (int&) is a permanent alias. A pointer (int*) is a variable holding an address. Both let one piece of code touch another's data.

reference int&pointer int*
can be nullno, must bind at creationyes, nullptr
can re-target laterno, bound onceyes, assign a new address
syntax to usejust the name*p to dereference
arithmeticnonep++, p + i

Rule of thumb in modern C++: use references when you can, pointers when you must (optional "might not exist" values, dynamic memory, walking arrays, linked structures). That is why lesson 4-2's function parameters used references: the callee always had something real to bind to.

Quiz

Which statement is true of references but NOT of pointers?

Code exercise · cpp

Your turn. Sum the array using ONLY the pointer p and dereferencing (do not write a[i] anywhere). Expected output: `sum = 100`.