字符数组后的奇怪字符

问题描述:

我是 C 的真正初学者,但我正在学习!

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 so I can learn.

我制作了一个程序,它允许您输入 5 个字符,然后显示您所写的字符并还原它们,例如:asdfg"-gfdsa".奇怪的是,在输入的原始字符后面显示了一个奇怪的字符.

I have made a program which allows you to input 5 characters and then show the characters you wrote and also revert them, example: "asdfg" - "gfdsa". The weird thing is that a weird character is shown after the original characters that was inputted.

代码如下:

char str[5];
char outcome[] = "OOOOO";
int i;
int u;

printf("Enter five characters\n");

scanf("%s", str);

for(i = 4, u = 0; i >=0; u++, i--){
    outcome[i] = str[u];
}

printf("\nYou wrote: %s. The outcome is: %s.", str , outcome);


return 0;

如果我输入:asdfg",它会显示:asdfg♣",这是为什么?

If I enter: "asdfg" it shows: "asdfg♣", why is that?

感谢您的时间,请解释您的答案:)

Thank you for your time and please explain your answers :)

因为没有空终止符.在 C 中,字符串"是一系列连续字节(字符),以称为空终止符 ('\0') 的标记字符结尾.您的代码接受用户的输入并填充所有 5 个字符,因此您的字符串没有结尾".然后,当您打印字符串时,它将打印您的 5 个字符 ("asdfg"),并且它将继续打印堆栈中的任何垃圾,直到遇到空终止符为止.

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

限制格式指定器的好处是,即使输入长度超过 5 个字符,也只会将 5 个字符存储到您的字符串中,并且始终为空终止符留出空间.

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.