0

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.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
user12074577
  • 1,371
  • 8
  • 25
  • 30

1 Answers1

1

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.

Christian Garbin
  • 2,512
  • 1
  • 23
  • 31