by happytoexplain · 2y ago · 0 comments
> The sizeof way is the right way iff you are dealing with arrays not received as parameters. An array sent as a parameter to a function is treated as a pointer
The conclusion is that it's impossible in that scenario, so you can only manually keep track.
But isn't this what dereferencing is for? What's my fundamental misunderstanding?
In C, there are arrays. If you use the identifier that names the array as a parameter to a function, it gets quietly converted to a pointer to the first item of the array and all array size information is lost.
So you can obtain the array size, but only if you are dealing with the identifier that directly names the array. If you attempt the same technique on a pointer to the array, bad things will happen.
Technically a pointer to the array will work as expected (i.e. void f(int (*x)[5])).
However, if you have a function parameter spelled `T array[N]`, that's really just a `T *array` with a helpful hint that it probably points to the beginning of an array of `N` `T`s. But it might not...
For the case of the function parameter, `sizeof array` is `sizeof(T*)`.
If you make an array 6 long, the compiler knows you did that. However, that information isn’t stored in heap anywhere. If all you have is sizeof(somePtr), there’s nothing for it to look at to retrieve the data.
This question really needs an answer that's carefully written to handle all 6 cases {C, C++ (since this belongs in a header)} x { normal array, VLA, pointer-which-is-an-error }
Over time people realized this is kinda dumb and annoying, so now C++ has std::span, Rust has slices, which are basically structures that store both a pointer and a size, so you can define functions like void do_something(std::span<int> numbers). C will remain forever though so we have to forever deal with the above