Strange character after an array of characters

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.

Leave a Comment