9

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 :)

user2166357
  • 127
  • 1
  • 1
  • 7
  • 2
    You need to terminate the array of characters. See http://stackoverflow.com/questions/10943033/why-are-strings-in-c-usually-terminated-with-0 – bn. Mar 22 '13 at 18:13

2 Answers2

21

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.

Mike
  • 47,263
  • 29
  • 113
  • 177
2

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'
  • `scanf()` will set the terminator for you when handling a `%s` format specifier. That said, `scanf()` in combination with `%s` should be avoided in the first place, as it is a clear-and-present danger for buffer overflows. Use `fgets()` instead. – WhozCraig Mar 22 '13 at 18:13