【发布时间】:2014-09-10 12:35:33
【问题描述】:
在下面的代码中:
#include <stdio.h>
int main(){
char *name;
int age;
char *gen;
printf("Your name:");
scanf("%s",name);
printf("Your age:");
scanf("%d",&age);
printf("Your gender:");
scanf("%s",gen);
printf("*****************\n");
printf("%s is a %d years old %s \n",name,age,gen);
return 0;
}
当我这样运行它时:
Your name:tom
Your age:20
Your gender:male
*****************
tom is a 20 years old (null)
如您所见,gen 是一个空值,为什么scanf 读入 gen 失败而前两次读成功?
【问题讨论】:
-
所以代替 char *name 使用 char name[20] 和 char gen[20]
-
@Rob 为什么
name不分配内存就可以工作,而gen不行? -
@user3289218 “运气”。未定义行为的最严重症状。
-
你在鼻恶魔领域,任何事情都有可能发生。哦,你的代码中没有 null 值(或者至少,没有值保证为 null;在 Microsoft 调试环境中,保证 not 是)。
-
是的,昆汀是对的。你很幸运,指向名称的指针没有指向重要的东西。你基本上写在内存中的某个地方,你可能已经写入了未分配的内存或在某处损坏了另一个变量或弄乱了函数的指令..没有办法知道。因此,您的代码行为未定义。