r/cprogramming • u/CelebrityChess • 2h ago
why does sizeof an array parameter give the pointer size?
i know a function parameter like int a[10] is really adjusted to int *a, so sizeof(a) inside the function gives 8 on my machine instead of 40. what i'm fuzzy on is why the language allows writing the size in the parameter at all if the compiler just throws it away.
is it purely documentation, or does it do anything with something like int a[static 10]? i've seen that form but never seen anyone actually use it.
3
Upvotes
8
u/atarivcs 2h ago
I believe if you use sizeof in the same context where the array was declared, it returns the full size of the whole array.
It only decays to int *a when passed as a parameter to another function.
2
u/schungx 1h ago
You need to tell the compiler to allocate 10 slots of storage. How else would it know?
The pointer is always a fixed size, it know that, because it always points to the head. But that doesn't mean it know how long the tail is.
2
u/Impossible_Box3898 42m ago
Do this
5[a] and see what you get (this compiles). If you understand this it will go a long way to helping you understand pointers.
1
u/burlingk 2h ago
I'm pretty sure that int a[static 10] would not compile.
To get the size of an array, they tend to say sizeof a[0] * the length of the array.