I wrote the following C program:
int main(int argc, char** argv) {
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
printf("%s", strcat(str1, str2));
return (EXIT_SUCCESS);
}
I want to concatenate the two strings, but it doesn't work.
This question is related to
c
strcat
concats str2
onto str1
You'll get runtime errors because str1
is not being properly allocated for concatenation
When you use string literals, such as "this is a string"
and in your case "sssss"
and "kkkk"
, the compiler puts them in read-only memory. However, strcat
attempts to write the second argument after the first. You can solve this problem by making a sufficiently sized destination buffer and write to that.
char destination[10]; // 5 times s, 4 times k, one zero-terminator
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
strcpy(destination, str1);
printf("%s",strcat(destination,str2));
Note that in recent compilers, you usually get a warning for casting string literals to non-const character pointers.
Here is a working solution:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char str1[16];
char str2[16];
strcpy(str1, "sssss");
strcpy(str2, "kkkk");
strcat(str1, str2);
printf("%s", str1);
return 0;
}
Output:
ssssskkkk
You have to allocate memory for your strings. In the above code, I declare str1
and str2
as character arrays containing 16 characters. I used strcpy
to copy characters of string literals into them, and strcat
to append the characters of str2
to the end of str1
. Here is how these character arrays look like during the execution of the program:
After declaration (both are empty):
str1: [][][][][][][][][][][][][][][][][][][][]
str2: [][][][][][][][][][][][][][][][][][][][]
After calling strcpy (\0 is the string terminator zero byte):
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
After calling strcat:
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
strcat
attempts to append the second parameter to the first. This won't work since you are assigning implicitly sized constant strings.
If all you want to do is print two strings out
printf("%s%s",str1,str2);
Would do.
You could do something like
char *str1 = calloc(sizeof("SSSS")+sizeof("KKKK")+1,sizeof *str1);
strcpy(str1,"SSSS");
strcat(str1,str2);
to create a concatenated string; however strongly consider using strncat/strncpy instead. And read the man pages carefully for the above. (oh and don't forget to free
str1 at the end).
strcat(str1, str2)
appends str2 after str1. It requires str1 to have enough space to hold str2. In you code, str1 and str2 are all string constants, so it should not work. You may try this way:
char str1[1024];
char *str2 = "kkkk";
strcpy(str1, "ssssss");
strcat(str1, str2);
printf("%s", str1);
Source: Stackoverflow.com