[英]What happens if I pass a variable value instead of a variable reference in scanf?
I have this code:我有这个代码:
int a;
scanf("%d", &a);
printf("You entered: %d", a);
which works perfectly fine, but I wondered what would happen if I pass the variable value instead of the variable reference in scanf
like scanf("%d", a)
.这工作得很好,但我想知道如果我传递变量值而不是像
scanf("%d", a)
这样的scanf
中的变量引用会发生什么。
I don't get an error from the compiler but there is no output either.我没有从编译器得到错误,但也没有 output 。 What is happening here?
这里发生了什么?
In scanf "%d"
is expecting a pointer to int
meaning a pointer to the address of the variable where the value will be stored, if you pass a
you will just be passing int
there is no way the value can be stored because scanf
won't know where.在 scanf 中,
"%d"
期望一个指向int
的指针,这意味着一个指向将存储值的变量地址的指针,如果你传递a
你将只是传递int
没有办法存储值,因为scanf
赢了不知道在哪里。
Doing this will invoke undefined behavior .这样做将调用未定义的行为。
Basically the & is an operator that returns the address of the operand.基本上 & 是一个返回操作数地址的运算符。 If you give in scanf the variable a without the &, it will be passed to it by-value, which means scanf will not be able to set its value for you to see.
如果你在 scanf 中给出不带 & 的变量 a,它将按值传递给它,这意味着 scanf 将无法设置它的值供你查看。 Passing it by-reference - using & actually passes a pointer to a - allows scanf to set it.
通过引用传递它 - 使用 & 实际上传递一个指向 a 的指针 - 允许 scanf 设置它。
scanf
expects the argument corresponding to the %d
conversion specifier to be the address of an int
object (with type int *
). scanf
期望与%d
转换说明符对应的参数是int
object (类型为int *
)的地址。 Whatever value a
contains will be interpreted as an address 1 . a
包含的任何值都将被解释为地址1 。
The behavior on doing this is undefined - the compiler isn't required to issue a diagnostic during translation, and the runtime environment isn't required to throw any kind of exception.这样做的行为是未定义的 - 编译器不需要在翻译期间发出诊断,并且运行时环境不需要抛出任何类型的异常。 Depending on the value contained in
a
you may get a runtime error, or you may clobber another data object, or your code may work without any apparent errors, or something completely different may happen.根据
a
中包含的值,您可能会遇到运行时错误,或者您可能会破坏另一个数据 object,或者您的代码可能会在没有任何明显错误的情况下运行,或者可能会发生完全不同的事情。
sizeof (int) == sizeof (int *)
- for a system like x86_64, that's not the case, so scanf
will treat bytes outside of a
as part of an address.sizeof (int) == sizeof (int *)
的系统上 - 对于像 x86_64 这样的系统,情况并非如此,因此scanf
会将a
之外的字节视为地址的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.