string array with garbage character at end

前端 未结 7 2136
遇见更好的自我
遇见更好的自我 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:55

    The only thing you are passing to the printf() function is a pointer to the first character of your string. printf() has no way of knowing the size of your array. (It doesn't even know if it's an actual array, since a pointer is just a memory address.)

    printf() and all the standard c string functions assume that there is a 0 at the end of your string. printf() for example will keep printing characters in memory, starting at the char that you pass to the function, until it hits a 0.

    Therefore you should change your code to something like this:

    char Buffer[9]; //holds the byte stream
    int i=0;
    
    if( //user input event has occured ) 
    {
            Buffer[i] = charInput;
            i++;
    
            Buffer[i] = 0; // You can also assign the char '\0' to it to get the same result.
    
            // Display a response to input
            printf("Buffer is %s!\n", Buffer);
    
    }
    

提交回复
热议问题