I am taking my first look into the Windows API and upon encountering WNDCLASSX I couldn't help wondering why its member, cbSize, existed. The description of cbSize, per the MSDN is: The size, in bytes, of this structure. Set this member to sizeof(WNDCLASSEX). Be sure to set this member before calling the GetClassInfoEx function. This describes it, and hints at its purpose, but I don't undestand the necessity.
My question is this: Why would a struct ever need to store its own size? Wouldn't any function handling the struct have access to that information using sizeof?
It is because of memory alignment. By default memory is not aligned on one bye order and this happens. Memory is allocated on 4-byte chunks on 32bit systems.
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
A structure T cannot contain itself. How would you know its size? It would be impossible to do so, because the size of T would require you to know the size of T (because T contains another T ).
Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added between struct members, to ensure that the latter one uses the correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes.
Later versions of the Windows API may add new fields to the struct. If the struct has a size, then older code can call the API function, which only copies the fields that the old code is aware of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With