gpt4 book ai didi

c - scanf为short int的奇怪行为

转载 作者:行者123 更新时间:2023-12-02 05:44:24 25 4
gpt4 key购买 nike

代码如下:

#include <stdio.h>
main()
{
int m=123;
int n = 1234;
short int a;
a=~0;
if((a>>5)!=a){
printf("Logical Shift\n");
m=0;
}
else{
printf("Arithmetic Shift\n");
m=1;
}
scanf("%d",&a);
printf("%d\n", m);
}

scanf("%d",&a);行之后,m的值变为 0

我知道这可能是由scanf引起的:a的类型很短,输入的类型是int。但是,这如何影响m的值?

非常感谢 !

最佳答案

片段中m成为0的最可能原因是因为您为m分配了if语句主体中的此值,但是由于该代码包含 undefined 的行为,因此无法肯定地说。

关于在scanf需要short*时传递int*的可能故事
假设sizeof(short) = 2sizeof(int) == 4
输入主函数时,变量所在的堆栈通常看起来类似于以下内容:

  _
|short int (a) : scanf will try to read an int (4 bytes).
|_ 2 bytes : This part of memory will most
|int (n) : likely be overwritten
| :..
|
|_ 4 bytes
|int (m)
|
|
|_ 4 bytes
当您将 %d(即 int)读入不影响变量 a的变量 m中时,尽管 n很可能会覆盖其一部分。

undefined 的行为
尽管这都是猜谜游戏,因为您在使用scanf语句时调用了通常称为“ undefined 行为”的内容。
标准不能保证的一切都是UB,结果可能是任何东西。也许您会将数据写入到另一个属于不同变量的段中,或者可能使Universe崩溃。
没有人能保证我们能活着看到UB存在的另一天。

如何使用 short int读取 scanf使用 %hd,并确保将其传递给 short* ..我们住了一晚的UB已经足够了!

关于c - scanf为short int的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8556816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com