While doing some programs on strings, I have come across this little problem. The question which was asked to me was this - Write a pointer version of the function strcat(s,t) which copies the string t to the end of s. I wrote the program as this -
#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
char *s1, *s2;
printf("enter the first string\n");
scanf("%s",s1);
printf("Enter the second string\n");
scanf("%s",s2);
strcat(s1,s2);
printf("Strings concatenated\n");
printf("%s",s1);
return 0;
}
void strcat(char *s, char *t)
{
while(*s++)
;
while(*s++ = *t++)
;
}
I know i have done something(or many things) terribly wrong. Because whenever i try to run this code- it gives me segmentation fault. Like this-
Enter the first string
Hello
Enter the second string
Segmentation fault (core dumped)
It would be really helpful if someone points me out the flaw/flaws of my implementation. Thanks in advance.
Thank you very much guys, for such quick responses. But seems that wasn't the only problem. After writing the program like this-
#include<stdio.h>
void strcat(char *s, char *t);
int main()
{
char s1[20], s2[20];
printf("enter the first string\n");
scanf("%s",s1);
printf("Enter the second string\n");
scanf("%s",s2);
strcat(s1,s2);
printf("Strings concatenated\n");
printf("%s",s1);
return 0;
}
void strcat(char *s, char *t)
{
while(*s++)
;
while(*s++ = *t++)
;
}
It runs like this.
Enter the first string
Hello
Enter the second string
There
Hello
It only prints the first string i have entered. Now i think i have made some mistake on that strcat function too.