See “decay” in practice: when you pass a C array to a function, it becomes a pointer, and sizeof stops behaving the way you expect.
- Array-to-pointer decay: in many contexts,
int a[6]becomesint*. - A function parameter
int a[]is equivalent toint* a. sizeof(a)inside the function measures the pointer size, not the original array size.- Classic fix: pass pointer + size.
File: 03_array_to_pointer_decay.cpp
- In
main,ais a real array:sizeof(a)measures the entire array.std::size(a)returns the number of elements.
- Call
try_guess_size_bad(a):- Inside the function,
ais treated as a pointer. sizeof(a)is now the pointer size (for example 8 bytes on 64-bit).
- Inside the function,
- Call
print_with_size(a, std::size(a)), which works because the size is passed along.
- Trusting
sizeof(parameter)to figure out how many elements there are. - Writing
void f(int a[10])thinking it forces size 10 (it doesn’t; it still becomes a pointer). - Forgetting to pass the size and “guessing” in the loop.
- Change the type to
doubleand notice thatsizeof(a)inmainchanges, but inside the function it remains the pointer size. - Do
print_with_size(a + 2, 3)and print only part of the array. - Try compiling with extra warnings and see whether the compiler warns about
sizeofon the parameter.
g++ -std=c++20 -O2 -Wall -Wextra -pedantic -g 03_array_to_pointer_decay.cpp -o app
./app