strcat concat a char onto a string?

后端 未结 6 736
谎友^
谎友^ 2020-12-14 22:45

Using GDB, I find I get a segmentation fault when I attempt this operation:

strcat(string,¤tChar);

Given that string is initializ

6条回答
  •  死守一世寂寞
    2020-12-14 23:25

    Because ¤tChar is not a string, it doesn't finish with \0 character. You should define B as char *currentChar = 'B';. Also according to http://www.cplusplus.com/reference/clibrary/cstring/strcat string should have enough space to hold the result string (2 bytes in this case), but it is only 1 byte.

    Or if you want to use char then you can do something like (depending of your code):

    char string[256];
    ...
    
    char currentChar = 'B';
    size_t cur_len = strlen(string);
    if(cur_len < 254) {
        string[cur_len] = currentChar;
        string[cur_len+1] = '\0';
    }
    else
        printf("Not enough space");
    

提交回复
热议问题