Search code examples
carraysprintfformat-specifiers

Why does using the "%s" format specifier to printf an array of char output additional nonsense values after the final char in the array?


I stumbled upon this behavior that I am curious to understand.

I mistakenly wrote the following at the end of a program to print the elements in an array of char :

printf("output: %s",outputText[]);

when I should have (and ultimately did) iterate over the array and printed each element like so:

for(int i = 0; i < textLength; i++){

        printf("%c",outputText[i]);
    }

What prompted me to implement the latter was the output I was getting. Despite initializing the array to limit the characters to outputText[textLength], ensuring that there were no unexpected elements in the array, my output when implementing the former code would always be littered with additional spooky elements, like below:

spooky character additions

I've just run the same program three times in a row and got three random characters appended to the end of my array.

(Edit to replace outputText[] --> outputText in first example.)


Solution

  • %s is for strings; a string is a array of chars ending with NUL (0x00 in hex, or '\0' as character), so the printf() will print until it finds a NUL!

    If you set the last element of the array to NUL, printf will finish there.