how size of a structure varies with different data types

瘦欲@ 提交于 2019-12-01 21:19:47
Devolus

The difference in size is due to alignment. The compiler is free to choose padding bytes, which make the total size of a structure not necessarily the sum of its individual elements.

If the padding of a structure is undesired, because it might have to interface with some hardware requirement (or other reasons), compilers usually support packing structures, so the padding is disabled.

Deidrei

You definitely get Data Structure Alignment

"Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding."

For more, take a look at this, Data Structure Alignment

The C standard allows a compiler to add padding bytes to structs after any field to allow the following field to be aligned according to any specific requirements of the compiler (or the user of the compiler). The standard does not specify, but typically a compiler will provide a command line argument to specify the (default) alignment. Good compilers also invariably support the de facto standard of #pragma pack, including push and pop options.

Padding bytes provide improved performance by reducing the amount of memory accesses required by suitably aligned data types. For example, on a 32-bit processor (more specifically a system which uses memory with 32 data lines) accessing a 32-bit integer will require two memory accesses when reading and writing the value rather than just one if it crosses a 4-byte boundary (ie, unless the bottom two bits of the address of the integer are zero).

See My Blog Post for more details (better than Wikipedia article).

The magic word is padding/memory alignment @see data structure alignment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!