string array with garbage character at end

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

    In addition to the previous comments about zero termination, you also have to accept responsibility for not overflowing your own buffer. It doesn't stop at 8 characters because your code is not stopping! You need something like the following (piggy-backing onto Jeremy's suggestion):

    #define DATA_LENGTH 8
    #define BUFFER_LENGTH (DATA_LENGTH + 1)
    
    char Buffer[BUFFER_LENGTH]; //holds the byte stream
    int charPos=0;  //index to next character position to fill
    
    while (charPos <= DATA_LENGTH  ) { //user input event has occured
        Buffer[i] = charInput;
    
        Buffer[i+1] = '\0';
    
        // Display a response to input
        printf("Buffer is %s!\n", Buffer);
    
        i++; 
    
    }
    

    In other words, make sure to stop accepting data when the maximum length has been reached, regardless of what the environment tries to push at you.

提交回复
热议问题