当我使用这段代码时:
#include <stdio.h>
int main(void){
int hi, hello;
hi = 1;
hello = 100;
printf("%d and %d", &hi, &hello);
printf("\nPress any key to exit...");
getch();
}
Run Code Online (Sandbox Code Playgroud)
它打印:
2358876 and 2358872
Press any key to exit
Run Code Online (Sandbox Code Playgroud)
但是当我定义变量hi并将它们hello分别定义为整数时,它会做它应该做的事情.为什么要打印这些奇怪的数字?
Kei*_*son 10
改变这个:
printf("%d and %d", &hi, &hello);
Run Code Online (Sandbox Code Playgroud)
对此:
printf("%d and %d", hi, hello);
Run Code Online (Sandbox Code Playgroud)
您想要打印变量的值,而不是它们的地址.
如果你确实想打印他们的地址,你需要使用%p并将地址转换为void*:
printf("address of hi is %p\n", (void*)&hi);
Run Code Online (Sandbox Code Playgroud)
(您可能会因为scanf需要读取值的地址而感到困惑.)
如果你"将变量hi和hello分别定义为整数",则说你得到了正确的行为.我不知道你的意思; 如果你使用&hi和&hello在你的printf通话中,你总是会得到奇怪的价值观.