Search code examples
c++concatenationcstring

Concatenate cstrings c++


When I run this, I get no errors, but the string does not get concatenated. Could someone tell me what I'm getting wrong here.

char *con(const char str[], int n) {
    char * t = new char[60];
    int l = strlen(str);
    t[l] = '\0';
    if (n <= 0) {
        return t;
    } else {
        for (int i = 0; i < n; i++) {
            strcat(t, str);
        }
        return t;
    }
}

If I try and take out the:

int l = strlen(str);
t[l] = '\0';

Then the program crashes.


Solution

  • You have to start with an empty string.

    Replace:

    int l = strlen(str);
    t[l] = '\0';
    

    With:

    t[0] = '\0';
    

    Now str will be concatenated n times in t.

    The original code was leaving the first l-1 chars in t uninitialized.