如果我们从某个地址开始,我们如何确定变量在整个程序中占用的地址?

假设内存位置从地址100开始,请考虑:

int a; struct{ char b; struct{ short *c[20]; char d; }e; }f; double g; char *h; 

我知道地址为100-103,但是我很难确定当你有一个结构时会发生什么。 我知道结构的起始地址是基于最大的字段对齐的,整体结构的大小是最大字段的倍数,但是当两个结构如上所述嵌套时,我无法区分这两者。 另外,如果我们有一个指针或一个数字数组, short *c[20]我们如何确定这个声明占用的内存? 如果有人可以解释每一行的地址布局,我将非常感激。 更重要的是,我将理解为什么以这种方式分配内存的解释。

感谢您的时间。

没有真正的规则。 这取决于编译器。 关于你所保证的是, b的地址低于e的地址, c的地址低于d的地址。 并且每个struct的第一个元素的地址与struct的地址相同。 另一方面,对于任何结构之外的元素都没有任何保证。 编译器可以以任何方式分配afgh

在x86-16位:

 int a; // two bytes struct{ char b; // One byte. struct{ // Struct itself is aligned to the size of pointer short *c[20]; // pointers may be 2 or 4 bytes depending on compile mode. char d; // one byte }e; }f; double g; // 8 bytes aligned to 8 bytes. char *h; // 2 or 4 bytes. 

在x86-32位:

 int a; // four bytes. struct{ char b; // one byte. struct{ // struct padding to size of pointer. short *c[20]; // pointers are 4 bytes. char d; // one byte. }e; }f; double g; // 8 bytes, aligned to 8 bytes. char *h; // 4 bytes. 

在x86-64上:

 int a; // 4 bytes. struct{ char b; // One byte. struct{ // struct aligned to size of pointer short *c[20]; // Pointers are 4 or 8 bytes (typically 8) char d; // One byte. }e; }f; double g; // 8 bytes. Aligned to 8 bytes. char *h; // 4 or 8 byte pointer, aligned to size of pointer. 

在其他一些架构中,这是完全有效的:

 int a; // 8 bytes struct{ char b; // 4 bytes. struct{ // Struct is not aligned to anything. short *c[20]; // Pointers are 8 bytes. char d; // 4 bytes }e; }f; double g; // 12 bytes, aligned to 4 bytes. char *h; // pointers are 8 bytes. 

我会让你为每个例子做数学运算来计算实际地址是什么。 但就像其他人所说的那样,布局完全取决于编译器,如果不了解处理器的特定编译器/体系结构的规则,则无法确定。

每个指针需要32位或64位,具体取决于您的平台。 20个元素的数组大小是一个这样的元素的20倍,依此类推。

出于对齐原因,需要额外的空间。 存储器通常可以同时读/写几个字节,只要它们在同一个字或双字中。 字节100-103形成双字。 下一个从104开始……所有这些都完全取决于平台。 在某些平台上,读取非字对齐地址中的单词甚至是非法的。