string array with garbage character at end

前端 未结 7 2126
遇见更好的自我
遇见更好的自我 2020-11-29 11:29

I have a char array buffer that I am using to store characters that the user will input one by one. My code below works but has a few glitches that I can\'t figure out:

7条回答
  •  攒了一身酷
    2020-11-29 11:49

    Since Buffer is not initialized, it starts with all 9 garbage values. From the observed output, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th and 2 immediate next memory location(outside the array) elements are clearly 'T', 'T', 'W', '\0', '\0', '=', '\0', '\0', '\0'.

    Strings consume all the characters up until they see NULL character. That is why, in every iteration, as the array elements are assigned one by one, buffer is printed up to the part where a garbage NULL is present.

    That is to say, string has an undefined behavior if the character array doesn't end with '\0'. You can avoid this by having an extra space for '\0' at the end of the buffer.

提交回复
热议问题