Strange character after an array of characters

前端 未结 2 1209
囚心锁ツ
囚心锁ツ 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:08

    Your string str[5]; is too short.

    It should be

    str[6];
    

    And when you print it the code goes out of bound of that array.

    You also have to set a null terminating character to str[] array to mark the end of the array.

    str[5] = '\0'
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题