Home > OS >  How to concatenate two dynamic char arrays?
How to concatenate two dynamic char arrays?

Time:03-30

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. :(

CodePudding user response:

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.

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related