Pass Array

Pass Array in C++: When you pass an to a function you hand over the value. When you pass a raw array you hand over the address of the first element and nothing…

The Analogy: Handing Over a Street, Not the Houses

When you pass an int to a function you hand over the value. When you pass a raw array you hand over the address of the first element and nothing else — like telling a courier "start at number 12 and keep going". You have given them a starting point but not the length of the street, so unless you also tell them how many houses to visit, they will walk off the end.

This one asymmetry explains almost every array-parameter bug in C++: the array's size is part of its type, and that type is thrown away the moment it becomes a parameter.


Syntax or Core Structure

#include <iostream>
#include <array>
#include <vector>

// These three declarations are IDENTICAL to the compiler.
void a(int data[10]);
void b(int data[]);
void c(int* data);              // the truth: just a pointer

// So a raw array parameter always needs the length alongside it.
int sum(const int* data, std::size_t count) {
    int total = 0;
    for (std::size_t i = 0; i < count; ++i) { total += data[i]; }
    return total;
}

// std::array and std::vector keep their size -- no second parameter.
int sumVec(const std::vector<int>& data) {
    int total = 0;
    for (const int x : data) { total += x; }
    return total;
}

int main() {
    int raw[5]{1, 2, 3, 4, 5};
    std::cout << sizeof(raw) << "\n";              // 20 -- the whole array
    std::cout << sum(raw, 5) << "\n";              // 15

    std::vector<int> vec{1, 2, 3, 4, 5};
    std::cout << sumVec(vec) << "\n";              // 15
    return 0;
}

Inside sum, sizeof(data) would be 8 (a pointer), not 20. That is array decay: the array silently becomes a pointer to its first element.


Technical Depth: Decay and the Ways Around It

Arrays are always modifiable, whether you asked or not

There is no such thing as passing a raw array by value. Because only the address travels, the function edits the caller's data by default:

void zeroOut(int data[], std::size_t n) {
    for (std::size_t i = 0; i < n; ++i) { data[i] = 0; }
}

int scores[3]{7, 8, 9};
zeroOut(scores, 3);
std::cout << scores[0];             // 0 -- the caller's array changed

If the function should not modify anything, say so: const int* data or const int data[]. The const is your only protection.

Never compute the size inside the function

void broken(int data[]) {
    const std::size_t n = sizeof(data) / sizeof(data[0]);    // 8 / 4 == 2. Always.
    // ...
}

That idiom works only where the array's real type is visible — in the same scope it was declared. Across a function boundary it silently produces 2 on a 64-bit build with int, which is the sort of bug that passes small tests.

Four ways to pass a fixed-size array properly

1. Pointer plus count. The C way. Works with everything, including arrays that came from an old API.

double mean(const double* data, std::size_t count);

2. A reference to an array of exact size. No decay, so sizeof works, but the size is now welded into the signature.

void printFive(const int (&data)[5]) {
    for (const int x : data) { std::cout << x << " "; }   // range-for works!
}

3. A template on the size. The compiler deduces N, so one function serves every length with no decay.

template <std::size_t N>
int sumAny(const int (&data)[N]) {
    int total = 0;
    for (const int x : data) { total += x; }
    return total;
}

int a[3]{1, 2, 3};
int b[7]{1, 2, 3, 4, 5, 6, 7};
sumAny(a);      // N deduced as 3
sumAny(b);      // N deduced as 7

4. Use std::array or std::vector and stop worrying. They pass like any other object, carry .size() with them, and support .at(), iterators and algorithms.

int sumArr(const std::array<int, 5>& data);          // fixed size, size known
int sumVec(const std::vector<int>& data);            // any size, size known

Comparing the options

Parameter formSize known inside?Accepts any length?Copies?
int data[] / int* dataNo — pass a countYesNo
const int (&d)[5]YesNo, exactly 5No
template<std::size_t N> ... (&d)[N]YesYesNo
const std::array<int, 5>&YesNo, exactly 5No
const std::vector<int>&YesYesNo
std::vector<int>YesYesYes

Multidimensional arrays need every dimension but the first

void printGrid(int grid[][4], int rows);        // column count is mandatory

The compiler needs the column count to compute grid[r][c] as *(base + r * 4 + c). Omit it and the arithmetic is impossible. The template trick handles this too:

template <std::size_t R, std::size_t C>
void printAny(const int (&grid)[R][C]);

std::span: the modern answer (C++20)

std::span<T> is a pointer and a length travelling together. One parameter type accepts a raw array, a std::array, or a std::vector:

#include <span>

int sumSpan(std::span<const int> data) {
    int total = 0;
    for (const int x : data) { total += x; }
    return total;
}

int raw[3]{1, 2, 3};
std::array<int, 4> arr{1, 2, 3, 4};
std::vector<int> vec{1, 2, 3, 4, 5};
sumSpan(raw);  sumSpan(arr);  sumSpan(vec);      // all fine, no copies

A span does not own its data, so it dangles if the underlying container dies or reallocates. Use it for parameters, not for storage.


Real World Example: An Audio Level Meter

A tiny signal-processing pipeline. It receives samples from a C-style capture API (so raw pointers arrive whether we like them or not) and hands them to modern code as soon as possible.

#include <iostream>
#include <vector>
#include <array>
#include <cmath>
#include <algorithm>

// --- Layer 1: forced to speak C. Pointer plus count, const because read-only.
double peakLevel(const double* samples, std::size_t count) {
    double peak = 0.0;
    for (std::size_t i = 0; i < count; ++i) {
        peak = std::max(peak, std::abs(samples[i]));
    }
    return peak;
}

double rmsLevel(const double* samples, std::size_t count) {
    if (count == 0) { return 0.0; }
    double sumSquares = 0.0;
    for (std::size_t i = 0; i < count; ++i) {
        sumSquares += samples[i] * samples[i];
    }
    return std::sqrt(sumSquares / static_cast<double>(count));
}

// Modifies in place, so no const. Still needs the count.
void normalise(double* samples, std::size_t count) {
    const double peak = peakLevel(samples, count);
    if (peak <= 0.0) { return; }
    for (std::size_t i = 0; i < count; ++i) { samples[i] /= peak; }
}

// --- Layer 2: template on the length. Size travels with the type, no decay.
template <std::size_t N>
double averageOf(const double (&window)[N]) {
    double total = 0.0;
    for (const double x : window) { total += x; }
    return total / static_cast<double>(N);
}

// --- Layer 3: what our own code uses. Size is part of the object.
double peakLevel(const std::vector<double>& samples) {
    return peakLevel(samples.data(), samples.size());       // reuse layer 1
}

std::array<double, 3> bandLevels(const std::vector<double>& samples) {
    std::array<double, 3> bands{0.0, 0.0, 0.0};
    const std::size_t third = samples.size() / 3;
    if (third == 0) { return bands; }
    for (std::size_t b = 0; b < 3; ++b) {
        bands[b] = rmsLevel(samples.data() + b * third, third);
    }
    return bands;
}

int main() {
    // Pretend this came from a capture callback: raw buffer + length.
    double buffer[8]{0.1, -0.4, 0.9, -0.2, 0.5, -0.7, 0.3, -0.1};
    const std::size_t n = sizeof(buffer) / sizeof(buffer[0]);   // valid HERE only

    std::cout << "Peak: " << peakLevel(buffer, n) << "\n";      // 0.9
    std::cout << "RMS:  " << rmsLevel(buffer, n) << "\n";

    normalise(buffer, n);
    std::cout << "Peak after normalise: " << peakLevel(buffer, n) << "\n";   // 1

    double window[4]{1.0, 2.0, 3.0, 4.0};
    std::cout << "Window mean: " << averageOf(window) << "\n";  // N deduced as 4

    // Once inside our own code, use a vector and forget about lengths.
    const std::vector<double> track(buffer, buffer + n);
    std::cout << "Vector peak: " << peakLevel(track) << "\n";

    const std::array<double, 3> bands = bandLevels(track);
    for (const double b : bands) { std::cout << b << " "; }
    std::cout << "\n";
    return 0;
}

The layering is the lesson. Layer 1 takes const double* plus a std::size_t count because that is the only shape a C capture API can hand us; const marks peakLevel and rmsLevel as read-only, while normalise deliberately drops it because rewriting the buffer in place is its purpose — and note that nothing at the call site distinguishes the two, which is exactly why the names must. The sizeof(buffer) / sizeof(buffer[0]) division appears in main and nowhere else, because that is the only scope where buffer still has its true array type; the same expression inside peakLevel would compute 1 and quietly report the level of a single sample. averageOf uses the template-on-N form to show the alternative: the size rides along in the type, sizeof and range-based for both work, and the caller never passes a count — the cost being a fresh instantiation per distinct length. Layer 3 is where our own code lives: the std::vector overload of peakLevel shares a name with the raw version and simply forwards samples.data() and samples.size(), so the length can never be wrong. bandLevels then does pointer arithmetic on purpose — samples.data() + b * third hands each third of the track to rmsLevel with no copying at all — and returns a std::array<double, 3> by value, which is free and keeps its size for the caller.


Common Mistakes

  1. Using sizeof(param) / sizeof(param[0]) inside a function. The parameter is a pointer; you get 8/4 = 2 on a typical build. Always.
  2. Passing the array but forgetting the count, then guessing at a length in the body. One off-by-one and you are reading past the end.
  3. Omitting const on read-only array parameters. Raw arrays are modifiable by default, so a slip inside the function silently corrupts the caller's data.
  4. Assuming a length parameter is honest. sum(data, 100) on a 10-element array compiles perfectly and reads 90 elements of adjacent memory.
  5. Mixing up int (&d)[5] and int* d[5]. The first is a reference to an array of 5 ints; the second is an array of 5 pointers. The parentheses matter.
  6. Omitting the column count in a 2-D parameter. void f(int grid[][]) does not compile — the compiler cannot do the row arithmetic.
  7. Returning a raw array from a function. You cannot; you get a pointer, and if it pointed at a local it dangles. Return a std::array or std::vector.
  8. Storing a std::span as a member. It does not own anything and will outlive its data.

Best Practices

  • Prefer std::vector and std::array parameters. They carry their size, so the whole class of length bugs disappears.
  • In C++20, use std::span<const T> for read-only sequence parameters. One signature accepts raw arrays, std::array and std::vector.
  • When a raw array is unavoidable, keep the pointer and count adjacent in the parameter list and name the count clearly (count, sampleCount) — never n five parameters away from the data.
  • Mark every read-only array parameter const.
  • Compute a raw array's length only in the scope that declared it, and prefer std::size(arr) from <iterator> over the sizeof division.
  • Push raw pointers to the edges of your program. Convert to a container as soon as the data is yours.
  • Test with -fsanitize=address; overruns through array parameters are otherwise invisible.

Practice Exercises

  1. Prove the decay: Write void inspect(int data[10]) that prints sizeof(data), call it with a real 10-element array, and compare with sizeof printed in main. Explain the two numbers in a comment.
  2. Three signatures, one job: Write largest three times — as (const int*, std::size_t), as a template <std::size_t N> taking const int (&)[N], and as (const std::vector<int>&). Call all three on the same data and confirm identical results. Note which one you would put in a public header, and why.
  3. Off-by-one on purpose: Call your pointer-and-count version with a count one larger than the array, build with g++ -fsanitize=address, and paste the report into a comment. Then switch to a std::vector with .at() and show what happens instead.