Use of struct padding

坚强是说给别人听的谎言 提交于 2019-11-28 04:45:13

问题


What is the use of padding struct in C?


回答1:


Some architectures will perform better if only aligned accesses are made, so putting 32-bit objects on 32-bit boundaries, and 64-bit objects on 64-bit boundaries can improve the speed of your application.

Some architectures are completely incapable of making unaligned accesses, and on those architectures not padding can be a real disaster.




回答2:


See this Wikipedia article for more information, but basically it's to make sure that the struct occupies an exact number of bytes - which as Steve314 states means that sizeof is an exact multiple of the 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.

You should also know that while this was very important for a programmer to know about this, it's become less so now because it is often handled by the compiler for you. There will be compiler options that allow you to control the process though.



来源:https://stackoverflow.com/questions/4587470/use-of-struct-padding

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