如果“&"会发生什么不是放在"scanf"语句中? [英] What will happen if '&' is not put in a 'scanf' statement?

查看:68
本文介绍了如果“&"会发生什么不是放在"scanf"语句中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我去接受采访时被问到以下问题:

I had gone to an interview in which I was asked the question:

您如何看待以下内容?

What do you think about the following?

int i;
scanf ("%d", i);
printf ("i: %d\n", i);

我回答:

  • 程序将成功编译.
  • 它将打印错误的数字,但是它将一直运行到最后不会崩溃

我的回答是错误的.我不知所措.

The response that I made was wrong. I was overwhelmed.

此后,他们解雇了我

在某些情况下,该程序可能会崩溃并导致核心转储.

The program would crash in some cases and lead to an core dump.

我不明白为什么 程序崩溃?谁能解释我的原因?任何帮助表示赞赏.

I could not understand why the program would crash? Could anyone explain me the reason? Any help appreciated.

推荐答案

定义变量后,编译器会为该变量分配内存.

When a variable is defined, the compiler allocates memory for that variable.

int i;  // The compiler will allocate sizeof(int) bytes for i

上面定义的

i 尚未初始化,并且具有不确定的值.

i defined above is not initialized and have indeterminate value.

要将数据写入分配给 i 的内存位置,您需要指定变量的地址.声明

To write data to that memory location allocated for i, you need to specify the address of the variable. The statement

scanf("%d", &i);

将由用户将 int 数据写入分配给 i 的内存位置.

will write an int data by the user to the memory location allocated for i.

如果未将& 放在 i 之前,则 scanf 将尝试将输入数据写入存储位置 i而不是& i .由于 i 包含不​​确定的值,因此可能存在与内存地址的值相等的值,或者可能包含超出内存地址范围的值.

If & is not placed before i, then scanf will try to write the input data to the memory location i instead of &i. Since i contains indeterminate value, there are some possibilities that it may contain a value equivalent to the value of a memory address or it may contain a value which is out of range of memory address.

在任何一种情况下,程序都可能会出现异常行为,并导致未定义的行为.在这种情况下,什么都可能发生.

In either case, the program may behave erratically and will lead to undefined behavior. In that case anything could happen.

这篇关于如果“&"会发生什么不是放在"scanf"语句中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆