strcat concat a char onto a string?

后端 未结 6 733
谎友^
谎友^ 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:03

    As responded by others, ¤tChar is a pointer to char or char*, but a string in C is char[] or const char*.

    One way to use strcat to concatenate a char to string is creating a minimum string and use it to transform a char into string.

    Example:

    Making a simple string, with only 1 character and the suffix '\0';

    char cToStr[2];
    cToStr[1] = '\0';
    

    Applying to your question:

    char * string = "";
    char currentChar = 'B';
    

    cToStr will assume the string "B":

    cToStr[0] = currentChar;
    

    And strcat will work!

    strcat ( string, cToStr );
    

提交回复
热议问题