I want to append two strings. I used the following command:
new_str = strcat(str1, str2);
This command changes the value of str1
. I want new_str
to be the concatanation of str1
and str2
and at the same time str1
is not to be changed.
In the C Programming Language, the strcat function appends a copy of the string pointed to by s2 to the end of the string pointed to by s1. It returns a pointer to s1 where the resulting concatenated string resides.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
String Concatenation and String Appending You can concatenate in any order, such as concatenating str1 between str2 and str3 . Appending strings refers to appending one or more strings to the end of another string. In some cases, these terms are absolutely interchangeable.
You need to allocate new space as well. Consider this code fragment:
char * new_str ; if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){ new_str[0] = '\0'; // ensures the memory is an empty string strcat(new_str,str1); strcat(new_str,str2); } else { fprintf(STDERR,"malloc failed!\n"); // exit? }
You might want to consider strnlen(3)
which is slightly safer.
Updated, see above. In some versions of the C runtime, the memory returned by malloc
isn't initialized to 0. Setting the first byte of new_str
to zero ensures that it looks like an empty string to strcat.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With