Strange character after an array of characters

前端 未结 2 1215
囚心锁ツ
囚心锁ツ 2020-12-03 12:27

I am a real beginner to C, but I am learning!

I\'ve stumbled upon this problem before and decided to ask what the reason for it is. And please explain your answers s

2条回答
  •  不知归路
    2020-12-03 13:12

    Because there's no null terminator. In C a "string" is a sequence of continuous bytes (chars) that end with a sentinel character called a null terminator ('\0'). Your code takes the input from the user and fills all 5 characters, so there's no "end" to your string. Then when you print the string it will print your 5 characters ("asdfg") and it will continue to print whatever garbage is on the stack until it hits a null terminator.

    char str[6] = {'\0'}; //5 + 1 for '\0', initialize it to an empty string
    ...
    printf("Enter five characters\n");
    scanf("%5s", str);  // limit the input to 5 characters
    

    The nice thing about the limit format specificer is that even if the input is longer than 5 characters, only 5 will be stored into your string, always leaving room for that null terminator.

提交回复
热议问题