Pointers and Arrays

An array's items sit next to each other in memory, like houses in a row. The name of an array works like a pointer to its first item:

#include <iostream>
using namespace std;

int main() {
    int nums[4] = {10, 20, 30, 40};
    int* p = nums;              // same as &nums[0]
    cout << *p << "\n";         // 10
    cout << *(p + 1) << "\n";   // the next item: 20
    cout << *(p + 3) << "\n";   // 40
    cout << p[2] << "\n";       // [] works on pointers too: 30
    return 0;
}

Output

10
20
40
30

p + 1 doesn't mean “address plus one byte”. C++ knows p points to ints, so it moves forward by one whole int. This is called pointer arithmetic.

Walking through an array

#include <iostream>
using namespace std;

int main() {
    int nums[5] = {3, 6, 9, 12, 15};
    for (int* p = nums; p < nums + 5; p++) {
        cout << *p << " ";
    }
    cout << "\n";
    return 0;
}

Output

3 6 9 12 15 

Passing an array to a function

When you pass an array to a function, only the pointer to its first item is passed, so the function can't know the size. Pass the size as well:

#include <iostream>
using namespace std;

int sum(const int* values, int count) {
    int total = 0;
    for (int i = 0; i < count; i++) {
        total += values[i];
    }
    return total;
}

int main() {
    int data[] = {1, 2, 3, 4, 5};
    cout << sum(data, 5) << "\n";
    return 0;
}

Output

15

Tip: This is one reason vector is nicer: it always knows its own size().

HOME LABS COMMUNITY DASHBOARD