Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string append

Tags:

c

string

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.

like image 693
Udara S.S Liyanage Avatar asked May 05 '11 16:05

Udara S.S Liyanage


People also ask

Is there append function in C?

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.

How do you append a string?

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.

Can append be used in string?

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.


1 Answers

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.

like image 144
Charlie Martin Avatar answered Sep 30 '22 05:09

Charlie Martin