string literals into a "dynamic array"

closed account (EwCjE3v7)
Write a program to concatenate two string literals, putting the result in a dynamically allocated array of char.


 
char *name = new char[11]("Header " "Test");



array 'new' cannot have initialization arguments


Same problem even if I were to take the "Test" away, I still get the same error, how would I assign or initialize a "dynamic array" from a string literal?
Maybe something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>

char* concatenate(const char *str1, const char *str2)
{
    char *ret;
    unsigned int len1 = 0;
    unsigned int len2 = 0;
    unsigned int len3;
    
    while (*(str1 + len1) != '\0')
        ++len1;
    while (*(str2 + len2) != '\0')
        ++len2;
    
    len3 = len1 + len2 + 1;
    ret = new char[len3];
    for (unsigned int i = 0; i < len3; ++i)
    {
        if (i < len1)
            ret[i] = str1[i];
        else if (i < len1 + len2)
            ret[i] = str2[i - len1];
        else
            ret[i] = '\0';
    }
    return ret;
}

int main()
{
    char *str = concatenate("Hello,", " World!");
    std::cout << str;
    delete[] str;
    return 0;
}
closed account (EwCjE3v7)
Thank you mate, cheers!
Topic archived. No new replies allowed.