Friday 23 August 2013

Implementing strcat using pointers

Implementing strcat using pointers

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.

No comments:

Post a Comment