-3

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

zangiku
  • 57
  • 1
  • 12

3 Answers3

5

%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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Gustavo Laureano
  • 556
  • 2
  • 10
2

You are probably missing the '\0' character as the element of the character array that marks the end of the string.

JFMR
  • 23,265
  • 4
  • 52
  • 76
1

You are missing string terminating character \0 end of the string. So, make your string is \0 terminated. Like:

outputText[textLength-1] = '\0';
msc
  • 33,420
  • 29
  • 119
  • 214