简体   繁体   中英

Strange character after an array of characters

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.

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.

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?

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM