gpt4 book ai didi

c - 数据类型和格式说明符

转载 作者:太空宇宙 更新时间:2023-11-04 07:45:11 25 4
gpt4 key购买 nike

如果我为 id 变量传递错误排序的类型说明符,为什么 input 变量的值设置为零?

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define MAX 100
int main()
{
int i=0;
int input;
char *name=(char *)malloc(sizeof(char)*MAX);
unsigned short int id;

printf("\nPlease enter input:\t");
scanf("%d", &input);
getchar();//to take \n

printf("\nEnter name.....\n");
fgets(name,MAX,stdin);

printf("\nEnter id: ");
scanf("%uh",&id);//type specifier should have been %hu
printf("%d",input);//value set to 0?
}

为什么 inputscanf("%uh", &id) 覆盖了?

最佳答案

乔蒂·拉瓦特

你有我所说的内存溢出错误。微软 (Visual Studio) 称它为:

"Stack around the variable ‘id’ was corrupted"

并非所有计算机系统都以相同的方式处理内存溢出错误。 Visual Studio/Windows 捕获此错误并引发异常。

enter image description here

OpenVMS 只会执行指令,然后继续执行下一条指令。在任何一种情况下,如果程序继续运行,其行为都将是未定义的。

在英语中,您正在将更多数据位写入无法包含它的变量中。额外的位被写入未分配给变量的其他内存位置。正如 chux 所提到的,后面的语句将具有未定义的行为。

解决方案:

正如您已经知道并被其他人提到的那样,将格式说明符从“uh”更改为“hu”。

关于您的代码的注意事项:

  • 正如我的 Adrian 所说,使用“hu”作为格式说明符是可行的。该说明符需要一个指向 unsigned short int 变量的指针。 Click here to go to scanf format specifiers wiki page.
  • 当您指定“%uh”时,scanf 会删除 %u 作为格式说明符并将其余部分 ('h') 视为要忽略的文本。
  • 格式说明符“u”需要一个指向无符号整型变量 (unsigned int *) 的指针。
  • 格式说明符“hu”需要一个指向无符号短变量的指针(unsigned short整数 *).

关于c - 数据类型和格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764954/

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