Search code examples
cc-strings

Having some trouble with string.h library in C


I have run this code in C,

char *bracket_by_len(char *output, char *word, int length)
{
    if(strlen(word) < 5) {
        output[0] = '<';
        output[1] = '<';

        /*int i = 2;
        while(i != (strlen(word) + 2)) {
            output[i] = word[i - 2];
            i += 1;
        }*/

        strncat(output, word, strlen(word));
        strcat(output, ">>");
return output;
} else {... not using them as 4 letter word for input}

int main()
{
    char word[40], output[40]; // word is not used.
    printf("%s \n.", bracket_by_len(output, "word", 20);
    return 0;
}

The actual code is this:Input code. I then wrote

return output;

I printed this with

printf("Based on size, \t %s.\n", output);

And the output looks like this:

Based on size, <<^S>>.

There are some random characters in the beginning. When I replaced the strncat() function by a while loop with manually copying the letters of the word, the input is alright.

Thanks in advance.


Solution

  • output hasn't been terminated with a NULL. Add it after the left chevrons.

    output[0] = '<';
    output[1] = '<';
    output[2] = 0;
    strncat(output, word, strlen(word));
    printf("%s\n", output);
    

    If you use sprintf in stead you won't have to worry about adding the null that detail.

    sprintf(output, "<<");
    strncat(output, word, strlen(word));
    printf("%s\n", output);