Search code examples
cstringconcatenationc-stringsstrcat

Access violation with strcat()


In my code i have a for loop to concat char by char from another array starting from a certain point. So for example if the text is "hi i need help" and my starting index is 10 it would concat "help" to the end of char* rs.

for (int l = start_index; l < strlen(text); l++) {
    strcat(rs, "h");
}

I tested the above and it works fine with no errors, but this

for (int l = start_index; l < strlen(text); l++) {
    strcat(rs, text[l]);
}

does not. According to the debugger "text" is char[256] and "rs" is a *char if that helps. The debugger also shows text[l] is of the correct value in that enumeration.


Solution

  • The strcat function takes two strings (pointers to char) as arguments. From the context it seems that text[l] is a single char which can't be used.

    One way to work around that is to create a small one-character temporary string for the character:

    for (int l = start_index; l < strlen(text); l++) {
        char temp[] = { text[l], '\0' };  // Don't forget the terminator
        strcat(rs, temp);
    }
    

    Another solution is to not use strcat at all, and instead use indexing of the rs string to assign directly to the elements of the string:

    size_t end_of_rs = strlen(rs);
    for (int l = start_index; l < strlen(text); l++) {
        rs[end_of_rs++] = text[l];
    }
    rs[end_of_rs] = '\0';  // Make sure string is terminated
    

    Or a much simpler solution: Concatenate directly from text:

    strcat(rs, &text[start_index]);
    

    But for this you should make sure that start_index isn't beyond the end of text (i.e. you need to verify that start_index < strlen(text)).