简体   繁体   English

为什么在增加的内存位置中没有连续定义的变量?

[英]Why aren't consecutively-defined variables in increasing memory locations?

If we take the following code:如果我们采用以下代码:

int height = 10;
int width = 5;
printf(
    "The memory address of height is: %p\n"
    "The memory address of width is:  %p\n",
    &height, &width
);

I get the following prints:我得到以下打印:

The memory address of height is: 0x7ffeed809a78
The memory address of width is:  0x7ffeed809a74

I was expecting the width to be at location 0x7ffee8843a7c .我期望宽度位于0x7ffee8843a7c位置。 In other words it's doing &height - 1 instead of &height + 1 .换句话说,它正在执行&height - 1而不是&height + 1 Why is that so?为什么呢?

There's no reason for them to be, so the compiler does what's best for itself.他们没有理由这样做,所以编译器会为自己做最好的事情。

Complex compiler optimizations and efficient and linear memory layout don't all go together, so linear memory layout was sacrificed.复杂的编译器优化和高效的线性内存布局不能同时进行,因此牺牲了线性内存布局。

When you get to hashtables, you will learn how the most efficient algorithms lead to repeatable pseudo-random output order.当您使用哈希表时,您将了解最有效的算法如何导致可重复的伪随机输出顺序。 The symbol names are loaded into a hashtable when compiling;编译时符号名称会加载到哈希表中; and the function memory space could laid out by iterating over the global symbol table, which is therefore in some arbitrary order.并且函数内存空间可以通过迭代全局符号表来布局,因此它是任意顺序的。

In general you will find this is true.一般来说,你会发现这是真的。 Whenever the order isn't specified it will be let to fall however, and when algorithms are non-trivial, however isn't simple anymore.每当未指定顺序时,它就会下降,而当算法不平凡时,它就不再简单了。

Don't ever depend on order of symbols in memory layout.永远不要依赖于内存布局中的符号顺序。 It's not allowed.这不被允许。

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

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