如果“&"会发生什么不是放在"scanf"语句中?

编程入门 行业动态 更新时间:2024-10-10 04:29:04
本文介绍了如果“&"会发生什么不是放在"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"语句中?

本文发布于:2023-06-02 19:21:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457505.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:放在   语句   发生   amp   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!