变量地址因天气而异,我们是否显示?
Variable address varies weather we diplay it or not?
谁能解释一下?
考虑这个程序。我们故意写 modify dest[10]
以便看到 j
值被修改。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char source[] = "Hello";
int j = 100;
char dest[10];
dest[12] = 'A';
printf("j = %d \n", j);
fflush(stdout);
printf("j = %d \n", j);
fflush(stdout);
printf("*j = %p \n", &j); // comment this line to get another result!
return 0;
}
输出:
j = 4259940
j = 4259940
*j = 0x7ffcc4cdef74
但是如果我们注释显示 j
可变地址 printf("*j = %p \n", &j);
的行,我们会得到:
j = 100
j = 100
就像 j
存储在其他地方,而不是像第一个示例中那样仅存储在 dest
变量之后。
有什么解释吗?
如果地址未被占用,则变量不需要有任何存储地址。
编译器可以自由地仅将值保存在寄存器中或通过优化机制将其完全删除,并且仅直接使用常量值 100
。
当 j
未存储在堆栈中时,您可能会检查是否损坏了 dest
。
对象j
和dest
存储在哪里,是否存储,dest[10]
如何处理越界访问,都是编译器的选择。现代编译器会做很多复杂的事情来优化程序。当您省略打印 j
地址的语句时,编译器会做出不同的选择,并产生不同的结果。
谁能解释一下?
考虑这个程序。我们故意写 modify dest[10]
以便看到 j
值被修改。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char source[] = "Hello";
int j = 100;
char dest[10];
dest[12] = 'A';
printf("j = %d \n", j);
fflush(stdout);
printf("j = %d \n", j);
fflush(stdout);
printf("*j = %p \n", &j); // comment this line to get another result!
return 0;
}
输出:
j = 4259940
j = 4259940
*j = 0x7ffcc4cdef74
但是如果我们注释显示 j
可变地址 printf("*j = %p \n", &j);
的行,我们会得到:
j = 100
j = 100
就像 j
存储在其他地方,而不是像第一个示例中那样仅存储在 dest
变量之后。
有什么解释吗?
如果地址未被占用,则变量不需要有任何存储地址。
编译器可以自由地仅将值保存在寄存器中或通过优化机制将其完全删除,并且仅直接使用常量值 100
。
当 j
未存储在堆栈中时,您可能会检查是否损坏了 dest
。
对象j
和dest
存储在哪里,是否存储,dest[10]
如何处理越界访问,都是编译器的选择。现代编译器会做很多复杂的事情来优化程序。当您省略打印 j
地址的语句时,编译器会做出不同的选择,并产生不同的结果。