I’m learning C language…
I want to write a function that concatenates two strings.
I wrote a function but it doesn’t work;
it doesn’t give any error in compilation,
but while running it doesn’t do anything.
Here is my code:
char* str_sum(char* s1, char* s2){
int j = strlen(s1);
int i=0;
while(s2[i]){
s1[j]=s2[i];
j++;
i++;
}
return s1;
}
int main(){
char* s1, s2;
s1 = "Joe";
s2 = "Black";
printf("%s\n",sum_str(s1,s2));
return 0;
}
Your function could look like this:
Note that this function allocates new string which means you should
freethis data when you finish with this string. Also note that terminating character ('\0') is stored at the end of this char array so thatprintfcan “print” it properly.Here’s main:
Output:
Joe BlackNote that I have declared variables
s1,s2ands3like this:char *s1, *s2, *s3;. If I write it like this:char *s1, s2, s3;then variabless2ands3are no longer arrays of characters but only characters.Also note that this program:
will crash since it tries to change constant string literal
"Joe".s1is pointer to first character of this literal in this case.But this program will work fine and its output will be
Xoe:s1is an array initialized with string"Joe"so it’s OK to change it.