Why sizeof cannot recover a C array parameter's length
An array in a function's local scope has a compile-time type containing its element count when the size is fixed. Dividing its byte size by the size of one element gives the count. Once a function takes the array as a parameter in the usual C syntax, that parameter is a pointer. The original object size is no longer encoded in the parameter type.
The contract
Passing a count alongside the pointer lets the callee operate on either an entire array or a valid slice. The function should document whether the count means elements or bytes, what happens for an empty input, and whether the memory may be modified. A name such as sample_count is more informative than size when several units appear in one API.
A small executable example
#include <stddef.h>
#include <assert.h>
#include <stdio.h>
static unsigned count_nonzero(const unsigned *a, size_t n) {
unsigned count = 0;
for (size_t i = 0; i < n; ++i) if (a[i]) ++count;
return count;
}
int main(void) {
const unsigned samples[] = {0, 7, 0, 2};
size_t n = sizeof samples / sizeof samples[0];
assert(n == 4);
assert(count_nonzero(samples, n) == 2);
assert(count_nonzero(samples, 0) == 0);
puts("two nonzero samples");
}
two nonzero samples
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
This example returns unsigned because the tiny example count fits that type; a general API can return size_t instead. It is the caller's responsibility to ensure the count corresponds to readable elements. In production interfaces, use lengths derived from validated storage rather than lengths supplied by an untrusted header. A null pointer may be acceptable for a zero-length contract only if no operation requires a valid pointer.
Checks to add in your own project
Exercise the function with one element, an empty range, and a slice starting at a nonzero index. If an interface takes a byte length but processes words, verify how non-multiple lengths are handled. Review each loop against its stated upper bound and check that any multiplication converting element count to bytes is representable.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.