strcat concat a char onto a string?

后端 未结 6 721
谎友^
谎友^ 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 22:58

    Both of the strings must be null-terminated. A single char isn't null terminated, so it's undefined when strcat will stop concatenating characters to the end. Also, string must contain at least enough space for both the original string and resultant string.

    This works:

    char string[10] = "";
    char* currentChar = "B";
    strcat(string, currentChar);
    
    0 讨论(0)
  • 2020-12-14 23:03

    As responded by others, &currentChar 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 );
    
    0 讨论(0)
  • 2020-12-14 23:14

    I think the simplest method (not efficient) would be sprintf

    sprintf(str, "%s%c", str, chr);

    0 讨论(0)
  • 2020-12-14 23:15

    strcat() takes two '\0'-terminated strings. When you pass the address of a character, the routine will look at the memory that follows the character, looking for the terminator.

    Since you don't know what that memory even refers to, you should expect problems when your code accesses it.

    In addition to that, your string argument does not have room to have any characters appended to it. Where is that memory written to? It will attempt to write past the end of the memory associated with this string.

    0 讨论(0)
  • 2020-12-14 23:18

    The first argument of strcat must have enough space to hold the rest of the string. "" is a constant string and as such GCC does not allocate space.

    Make it an array with enough space:

    char buf[1024];
    
    strcat(buf, "");
    strcat(buf, "B");
    
    0 讨论(0)
  • 2020-12-14 23:25

    Because &currentChar 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");
    
    0 讨论(0)
提交回复
热议问题