My code:
printf("Enter a number : ");
scanf("%d", &number);
printf("%d is what I entered\n", &number);
I input 2
,
预期输出:2 is what I entered
实际输出:2293324 is what I entered
这里有什么问题?
printf("%d is what I entered\n", &number);
是错误的,因为%d
(in the printf
) 需要一个类型的参数int
, not int*
。这会调用未定义的行为 https://en.wikipedia.org/wiki/Undefined_behavior如 C11 标准草案 (n1570) 所示(强调我的):
7.21.6.1 fprintf 函数
[...]
- If a conversion specification is invalid, the behavior is undefined. 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
通过使用修复它
printf("%d is what I entered\n", number);
Then, 为什么scanf
要求&
变量名之前?
请记住,当您使用number
,你通过了value变量的number
当你使用&number
,你通过了address of number
(&
是地址运算符)。
So, scanf
不需要知道的值number
。它需要它的地址(int*
在本例中)以便将输入写入其中。
printf
另一方面,不需要地址。它只需要知道值(int
,在本例中)要打印。这就是为什么你不使用&
变量名之前printf
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)