FooContainer
is an array. Arrays in both C and C++ are guaranteed to not add padding between their elements. Any padding that may be present is only that which is internal to the element object type itself.
So yes, the sizeof
trick is a common technique that is guaranteed to work, so long as the parameter to sizeof
is indeed the name of an array, and not a pointer that was obtained by an array-to-pointer conversion.
Having said all that, since you tagged C++, try to avoid raw arrays. The C++ standard library has several alternatives that provide greater safety and more functionality.
And even if you do use a raw array, a better way to obtain the size in C++ would be with the help of the type system itself:
template<typename T, std::size_t N>
constexpr auto array_size(T(&)[N]) { return N; }
The above is very easy to use like so int structsincontainer = array_size(FooContainer);
and will only accept an array reference, instead of silently building when passed a pointer by accident.