why scanf scans a null value

2020-02-15 03:17发布

问题:

In the code below:

#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;  

}

When I run it like this:

Your name:tom
Your age:20
Your gender:male
*****************
tom is a 20 years old (null)

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

回答1:

char *name;
char *gen;

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

You can allocate memory for it like

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

OR define char array with predefined length

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


回答2:

char *name;
char *gen;

Are pointer, you need either to change to array

char name[256];//256 is arbitrary ofc
char gen[256];

or to allocate memory with your pointer:

char *name = malloc(256 * sizeof(*name));
char *gen = malloc(256 * sizeof(*gen));

Note that if you allocate memory with malloc, it is a good habbit to check if the allocation failed:

if (name == NULL)
    return -1;


标签: c scanf