Hello. Newbie working self through TC++PL.
Ex: 6.6.3: Write a function cat that concatenates 2 C-style strings. Use new to find store for the result.
My code:
Why does new give an array size of 20?
What am I doing wrong, and is my approach itself correct?
Ex: 6.6.3: Write a function cat that concatenates 2 C-style strings. Use new to find store for the result.
My code:
Code:
#include <iostream>
using namespace std;
char* cat(const char* str1, const char* str2){
char *catstr = new char[(strlen(str1) + strlen(str2) + 1)];
int i = 0;
for(; *str1; i++){
catstr[i] = *str1++;
}
for(;*str2;i++){
catstr[i] = *str2++;
}
return catstr;
}
int main() {
char str1[] = "Hello ";
char str2[] = "world!";
char *p = cat(str1, str2);
cout << p << endl;
return 0;
}
Why does new give an array size of 20?
What am I doing wrong, and is my approach itself correct?