为什么我在C中得到2个不同的值

时间:2013-09-21 18:56:02

标签: c

当我使用此代码时:

#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();
}

打印:

2358876 and 2358872

Press any key to exit

但是,当我将变量hihello分别定义为整数时,它会做它应该做的事情。为什么打印这些奇怪的数字?

3 个答案:

答案 0 :(得分:10)

改变这个:

printf("%d and %d", &hi, &hello);

到此:

printf("%d and %d", hi, hello);

您想要打印变量的,而不是它们的地址。

如果您确实要打印其地址,则需要使用%p并将地址转换为void*

printf("address of hi is %p\n", (void*)&hi);

(您可能对scanf需要其所读取的值的地址这一事实感到困惑。)

如果你“将变量hi和hello分别定义为整数”,那么你说你得到了正确的行为。我不知道你的意思;如果您在&hi来电中使用&helloprintf,那么您总是会得到奇怪的价值。

答案 1 :(得分:1)

您打印的不是变量的值,而是使用“&amp;”打印地址在你好和你好之前。
要打印值,您必须写下:
    printf("%d and %d", hi, hello);

答案 2 :(得分:1)

这是正确答案......

&用于指定地址...

由于两个变量不能具有相同的地址,因此每个变量

都会显示不同的变量

如果您想要打印一个值,请不要指定&amp;在印刷中。

例如

printf("%d",hi);    // will give you 1

printf("%d",&hi);   // Will always gives you different number every time on every machine

// It is showing address where the actual value of the variable hi is stored.. 
相关问题