为什么 scanf 扫描空值 [英] why scanf scans a null value

查看:41
本文介绍了为什么 scanf 扫描空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中:

#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 失败,但前两次读取成功?

As you can see, gen is a null value, Why scanf fails reading into gen but the first two readings success?

推荐答案

char *name;
char *gen;

只是字符指针,什么也不指向.所以需要为它分配内存.

are just char pointer and point nothing. So need to allocate memory for it.

你可以为它分配内存

char *name = malloc(100);
char *gen  = malloc(100);

OR 定义具有预定义长度的字符数组

OR define char array with predefined length

char name[100];
char gen[100];

这篇关于为什么 scanf 扫描空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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