Hi,
I am trying to learn C++, in the process I tried to write a function that gets two char pointers and concatenate the second one to the first one (I know there is strcat
for this).
But - what I want to accomplish is to modify the first parameter pointer so it will point to the result. for this reason I used a reference to pointer in the first parameter.
Before returning from the function I want to free the first parameter memory but I get an error.
Here is the code:
void str_cat(char*& str1, char* str2)
{
if (!str1)
{
str1 = str2;
return;
}
if (!str2)
return;
char * new_data = new char[strlen(str1) + strlen(str2) +1];
char * new_data_index = new_data;
char * str1_index = str1;
char * str2_index = str2;
while(*str1_index)
*new_data_index++ = *str1_index++;
while(*str2_index)
*new_data_index++ = *str2_index++;
*new_data_index = NULL;
delete str1; //ERROR HERE (I also tried delete[] str1)
str1 = new_data;
}
I do not understand why.
Any suggestions?
Thanks,
Itay\
EDIT Here is how I use the function
char * str1 = NULL;
char * str2 = NULL;
str_cat(str1, "abc");
str_cat(str2, "def");
str_cat(str1, str2);