3 ms·
sizeof() is evaluated at compile time: https://stackoverflow.com/questions/671790/how-does-sizeof-determine-the-size-of-an-array https://stackoverflow.com/quest
by kstrauser 2y ago
sizeof() is evaluated at compile time: https://stackoverflow.com/questions/671790/how-does-sizeof-determine-the-size-of-an-array https://stackoverflow.com/questions/671790/how-does-sizeof-d...
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.
- card_zero 2y agoYeah, it's a pointer which may happen to be a pointer to the start of an array ... or some other element of the array, or a different variable of the same type (the type of the element), or a variable of a different type coerced into being passed as the right type. The compiler doesn't know or care! Do what you like! Hence it can't tell you the size of the thing because the thing could be anything and could have come from anywhere.
- happytoexplain 2y agoWow, that's new to me! Like a macro in languages I'm used to, but smarter. This is key in contextualizing the "it's a pointer" part of the explanation. It sounds like the size of an array is never intrinsic to it, as a data type, regardless of whether what we've got is a pointer. What's important is that sizeof is compile-time, so it can only know the array size in contexts where it can be determined at compile time.
- kstrauser 2y agoYep, that’s correct. The entire data structure of a C array, as available to the running code, is a pointer to the first element. The compiler has that information during compilation but it doesn’t make it trough to the resulting executable.
- o11c 2y agoExcept, not always. For VLAs runtime is involved. 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 }