简体   繁体   English

结构如何保存在内存C中

[英]How structs are saved in memory C

How structs in C are saved in the memory? C中的结构如何保存在内存中?

Why sometimes the struct length in the memory is bigger than expected? 为什么有时存储器中的结构长度大于预期的长度?

That's called data structure alignment . 这就是所谓的数据结构对齐

Although not a perfect duplicate, you can find a good explanation of this in C at Structure padding and packing 尽管不是完美的副本,但是您可以在C的“ 结构填充和打包”中找到对此的很好解释。

  • Structs are stored as a concatenation of the variables they are declared to contain. 结构存储为声明包含的变量的串联。
  • The variables are stored in the order they are declared. 变量按照声明的顺序存储。 The address of the beginning of the struct is the address of the beginning of the first variable it contains. 结构开始的地址是它包含的第一个变量的开始的地址。
  • There may be a gap between the rest of the variables in the struct memory layout (or even at the end of the struct). 在结构内存布局中的其余变量之间(甚至在结构的末尾)可能存在间隙。 This is done to align the variables to memory addresses from which they can be fetched. 这样做是为了使变量与可以从中获取变量的内存地址对齐
    • Some architectures can only fetch aligned data. 有些架构只能获取对齐的数据。
    • Most architectures that can fetch unaligned data, suffer a performance penalty when doing so. 大多数可以获取未对齐数据的体系结构都会导致性能下降。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM