Malloc and scanf

前端 未结 5 1946
攒了一身酷
攒了一身酷 2021-01-18 19:19

I\'m fairly competent in a few scripting languages, but I\'m finally forcing myself to learn raw C. I\'m just playing around with some basic stuff (I/O right now). How can

5条回答
  •  -上瘾入骨i
    2021-01-18 19:49

    You need to give scanf a conversion format so it knows you want to read a string -- right now, you're just displaying whatever garbage happened to be in the memory you allocated. Rather than try to describe all the problems, here's some code that should at least be close to working:

    char *toParseStr = malloc(10);
    printf("Enter a string: ");
    scanf("%9s", toParseStr);
    printf("\n%s\n", toParsestr);
    /* Edit, added: */ 
    free(toParseStr);
    return 0;
    

    Edit: In this case, freeing the string doesn't make any real difference, but as others have pointed out, it is a good habit to cultivate nonetheless.

提交回复
热议问题