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

2
  • 5
    Are you missing the null character?
    – Ed Heal
    Commented May 25, 2017 at 10:07
  • 4
    printf("output: %s",outputText[]); is a syntax error
    – M.M
    Commented May 25, 2017 at 10:20

3 Answers 3

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.

2

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

1

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

outputText[textLength-1] = '\0';
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.