I want to concatenate strings in c. Therefore I wrote the following code:
#include <stdio.h>
#include <string.h>
int main () {
char str1[20], str2[20];
int i=0;
scanf("%20s",str1);
getchar();
scanf("%20s",str2);
getchar();
char str3[strlen(str1)+strlen(str2)];
for(i=0; str1[i]; i++){
str3[i]=str1[i];
}
for(i=0; str2[i]; i++){
str3[strlen(str1)+i]=str2[i];
}
printf("\nSum is: %s\n", str3);
return 0;
}
Why do I get random characters at the end of the sum str3? I know there are a function to do that, but I wanted to do it an elementary way.
Because you are invoking undefined behavior by having printf()
read out-of-bounds of str3
.
You must
char str3[strlen(str1)+strlen(str2)];
should be char str3[strlen(str1)+strlen(str2)+1];
str3[strlen(str1)+strlen(str2)] = '\0';
before the printf()
statement.