C语言 字符数组后的奇怪字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15577124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:48:21  来源:igfitidea点击:

Strange character after an array of characters

carraysstringcharacterscanf

提问by user2166357

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

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

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.

我之前偶然发现了这个问题,并决定询问它的原因是什么。请解释您的答案,以便我学习。

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.

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

Here is the code:

这是代码:

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;

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

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

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

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

回答by Mike

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.

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

char str[6] = {'
str[6];
'}; //5 + 1 for '
str[5] = '##代码##'
', 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.

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

回答by user2166357

Your string str[5];is too short.

你的字符串str[5];太短了。

It should be

它应该是

##代码##

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[] 数组设置一个空终止字符以标记数组的结尾。

##代码##