scanf string in c - why can i scan more than the char[] declaration?

后端 未结 4 1389
北荒
北荒 2021-01-16 10:15

I have a program where I need to scanf a string, which I know it will be only 2 characters long. (for example: \"ex\"). what is the proper way to do that?

I was goin

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 10:47

    but when I enter a 10-letter word it also works just fine. How come? Does the [3] has no meaning?

    I doesn't work fine. See in this example:

    #include 
    
    int
    main(int argc, char **argv)
    {
      char second[5] = "BBBB";
      char myStr[3] = {0};
    
      scanf("%s", myStr);
    
      printf("second = %s\n", second);
      printf("myStr  = %s\n", myStr);
    
      return 0;
    }
    

    writing only two characters in myStr is fine:

    a.exe
    AA
    second = BBBB
    myStr  = AA
    

    writing more data overrides the near by memory of second:

    a.exe
    AAAAAAA
    second = AAAA
    myStr  = AAAAAAA
    

    You need to limit the number of characters scanf reads using something like scanf("%2s", myStr);, 2 is the size of myStr - 1.

提交回复
热议问题