Strange character after an array of characters

33,210

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.

Share:
33,210
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

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