Segmentation fault while taking string from user

后端 未结 4 1045
说谎
说谎 2021-01-29 13:07

Code:

int main()
{
  char *name=NULL;
  int n;
  printf(\"\\nenter the string\\n\");
  scanf(\"%s\",name);
  n=strlen(name);
  printf(\"%d\",n);
  return 0;
}
         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 13:47

    Try this,

    int main()
    
    {
      char *name = malloc(sizeof( char ) * LENGTH); // define LENGTH as you desired
    
      int n;
      printf("\nenter the string\n");
      scanf("%s",name);
      n=strlen(name);
      printf("%d",n);
    
      free(name);
    }
    

    Problem is you did not allocate memory for pointer. So allocate memory tp pointer with malloc(BUFSIZE). Also at the end you have to free your allocated memory with free(name).

提交回复
热议问题