ParsaAi
ParsaAi

Reputation: 349

How to concatenate two dynamic char arrays?

I have two char arrays defined like this: char* str = new char[size]; How can I concatenate these two without creating an additional array? I wrote the code below but it doesn't work:

void append(char* str1, int size1, char* str2, int size2) {
    char* temp = str1;
    str1 = new char[size1+size2];

    for (int i = 0; i < size1; i++) {
        *(str1+i) = *(temp+i);
    }

    int j = 0;
    for (int i = size1; i < size1+size2; i++) {
        *(str1+i) = *(str2+j);
        j++;
    }

    delete[] temp;
}

I forgot to mention that this is a homework and I MUST do it this way despite the fact that std::string and etc. exist. :(

Upvotes: 0

Views: 670

Answers (2)

user18622327
user18622327

Reputation:

You can't concatenate if the result size of memory wasn't already allocated somewhere. But you shouldn't be struggling yourself with staff like that when you are in C++, you just have to do this:

string s1 = "some string one";
string s2 = "some string two";
s1 += s2; // or s1 = s1 + s2; appended, no need for loop and pointer copying.

Upvotes: 1

ParsaAi
ParsaAi

Reputation: 349

The problem of my code was not passing the str1 pointer by reference.
Here is the corrected code:

void append(char*& str1, int size1, char* str2, int size2) {
    char* temp = str1;
    str1 = new char[size1+size2];

    for (int i = 0; i < size1; i++) {
        *(str1+i) = *(temp+i);
    }

    int j = 0;
    for (int i = size1; i < size1+size2; i++) {
        *(str1+i) = *(str2+j);
        j++;
    }

    delete[] temp;
}

Upvotes: 0

Related Questions