Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why might a struct store its own size?

Tags:

c++

sizeof

winapi

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?

like image 848
Joseph Bleau Avatar asked Apr 30 '13 02:04

Joseph Bleau


People also ask

Why some structure variables occupy more size than expected?

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.

What is the size of struct always?

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.

Can a struct have itself?

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 ).

How is struct stored?

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.


1 Answers

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.

like image 162
Muscles Avatar answered Sep 19 '22 01:09

Muscles