skip to content

In C++, why does sizeof on an array function parameter give a pointer's size, and how do you keep the length?

level: middleimportance: should knowfreq 58%

answer

  1. the parameter is not an array
  2. adjusted to pointer to T
  3. the bound in brackets is ignored
  4. reference to array or std::span

basics

~20 s

A parameter declared as an array of T is adjusted to pointer to T, so the bound is discarded and sizeof yields the pointer's size. Keep the length with a separate size, a reference to array, std::array or C++20 std::span.

solid answer

~40 s

The standard adjusts any parameter of type "array of T" to "pointer to T" when it forms the function type, so `float sum(const float k[64])` is exactly `float sum(const float* k)`. The `64` is documentation only: callers can pass 9 floats or 1,000, and `sizeof(k)` is `sizeof(const float*)`. At the call site the argument undergoes array-to-pointer conversion, which is why it compiles. To keep the length, pass a pointer and a count, take `const float (&k)[N]` with `N` deduced by a template, use `std::array<float, N>`, or - in C++20 - `std::span<const float>`, which bundles pointer and size. Clang warns by default with `-Wsizeof-array-argument`.

code

cpp · 24 lines
cpp
#include <cstddef>
#include <iostream>
#include <span>

// The [64] is ignored: the parameter's type is adjusted to const float*.
float sum_decayed(const float kernel[64]) {
    std::size_t n = sizeof(kernel) / sizeof(kernel[0]);  // sizeof(const float*) / 4
    float s = 0;
    for (std::size_t i = 0; i < n; ++i) s += kernel[i];
    return s;
}

// A reference to an array keeps the bound in the type.
template <std::size_t N>
float sum_array(const float (&kernel)[N]) { float s = 0; for (float k : kernel) s += k; return s; }

// C++20: std::span carries the pointer and the length together.
float sum_span(std::span<const float> kernel) { float s = 0; for (float k : kernel) s += k; return s; }

int main() {
    float kernel[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1};
    std::cout << sum_decayed(kernel) << ' '      // 2 on a 64-bit target, not 9
              << sum_array(kernel) << ' ' << sum_span(kernel) << '\n';
}

go deeper

for a junior

Recall that an array parameter is really a pointer, so sizeof inside the function gives the pointer's size, and the length must travel separately.

for a middle

Name the adjustment rule, distinguish it from array-to-pointer conversion at the call site, and list reference-to-array, std::array and std::span as fixes.

for a senior

Explain that the bound in the parameter is never checked, so undersized buffers compile, and enforce span-based interfaces plus the sizeof warnings in code review.

for a principal

Decide when a library boundary should move from pointer-and-count to std::span, weighing C callers and ABI against bounds information at every call.

## The rule: array parameters are adjusted to pointers When C++ forms a function's type it takes each parameter's declared type and, among other adjustments, turns "array of `T`" into "pointer to `T`" and "function type" into "pointer to function". So these three declarations name the **same** function: ```cpp float sum(const float kernel[64]); float sum(const float kernel[]); float sum(const float* kernel); ``` The bound `64` survives only as a comment. Inside the body, `kernel` is a `const float*`, so `sizeof(kernel)` is the size of a pointer - 8 bytes on a 64-bit target - and the classic `sizeof(a) / sizeof(a[0])` idiom silently computes 2 instead of 64. There is a second, related mechanism at the call site: **array-to-pointer conversion**. An expression of type "array of N `T`" converts to a pointer to its first element in most contexts, which is why passing a `float[9]` to a parameter written `float[64]` compiles without complaint. People call both effects "decay"; the parameter adjustment is the one that loses information permanently. ## What the toolchain tells you Clang flags the idiom by default, with two separate diagnostics: - `-Wsizeof-array-argument`: "sizeof on array function parameter will return size of 'const float *' instead of 'const float[64]'". - `-Wsizeof-pointer-div`: "'sizeof (kernel)' will return the size of the pointer, not the array itself". GCC documents `-Wsizeof-pointer-div` too. Treat both as errors in a codebase that still has C-style buffers. ## Ways to keep the length | Technique | Signature | Length known | Notes | |---|---|---|---| | pointer plus count | `f(const float* p, std::size_t n)` | at run time | the C idiom; callers can pass a wrong `n` | | reference to array | `template <std::size_t N> f(const float (&a)[N])` | at compile time | one instantiation per size; only accepts real arrays | | `std::array` | `f(const std::array<float, 9>& a)` | in the type | size fixed by the signature or a template parameter | | `std::span` (C++20) | `f(std::span<const float> s)` | at run time | binds to C arrays, `std::array`, `std::vector`; cheap to pass by value | `std::span` is the modern default for "a contiguous run of elements I only look at": a non-owning view carrying a pointer and a size. Its static-extent form and `subspan` are covered with span and mdspan views; here it matters only as the parameter type that does not lose the length. ## Decay is everywhere arrays meet expressions For a real array `float kernel[9]` in the caller: 1. `float* p = kernel;` - the array converts to a pointer to `kernel[0]`. 2. `kernel + 1` - arithmetic happens on the converted pointer. 3. `auto copy = kernel;` - `auto` deduces `float*`, not an array. 4. `sizeof(kernel)`, `&kernel` and `decltype(kernel)` are the exceptions where the array type survives: `&kernel` is a `float (*)[9]`, a pointer to the whole array, whose `+ 1` steps by 36 bytes. 5. Multidimensional parameters decay only one level: `int img[][640]` becomes `int (*img)[640]`, so every inner bound but the first must be written and is enforced. ## Arrays cannot be passed or returned by value The adjustment rule has a mirror image for return types: a function cannot be declared to return an array at all, so `float make_kernel()[9];` is ill-formed. To move a fixed-size block in or out of a function by value, wrap it: `std::array<float, 9>` is an aggregate holding a real array member, so it copies, compares and returns like any other value, and its `size()` is a constant expression. A struct with an array member works the same way, which is how C code smuggles arrays through by value. This is also why a lambda that captures a C array by copy really does copy every element: the closure stores an array member, not a pointer. ## Why interviewers ask it The question tests whether a candidate distinguishes the **declared** type from the **adjusted** type. Strong answers: - name the adjustment rule, not "arrays are pointers" - they are not; an array object owns N elements, a pointer holds one address; - explain that the bound is not checked at the call, so passing a smaller buffer to a `float[64]` parameter compiles and any read past its end is undefined; - reach for a type that carries the length, `std::span` in C++20 code or a reference to array when the size is a compile-time fact; - notice that a template deducing `N` from `const float (&)[N]` is what `std::size` and `std::span`'s constructors from C arrays use under the hood.

  • Does writing int img[][640] as a parameter keep any bound at all?
    It keeps every bound except the first. The parameter is adjusted to `int (*img)[640]`, a pointer to an array of 640 ints, so the inner bound is part of the type and enforced: passing an `int[480][320]` is rejected. Only the outermost dimension is lost, which is why the row count still has to travel separately or in a type such as `std::mdspan` (C++23).
  • Why can std::span<const float> be passed by value without cost concerns?
    A dynamic-extent `std::span` holds just a pointer and a size, owns nothing and is trivially copyable, so copying it copies two scalars. Passing it by const reference would add an indirection for no benefit. The data it views must outlive the span, because it never extends the elements' lifetime.

  • An array parameter declared float a[64] is checked to have 64 elements
  • Arrays and pointers are the same thing in C++
  • sizeof(a) / sizeof(a[0]) works on any array parameter
  • Passing an array by value copies all its elements

Assumes C++20 for std::span; the parameter adjustment rule itself is unchanged since C++98.