allocated allocated - 28 days ago 5
C Question

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.

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.

Answer Source

1) In the main(), you have to allocate memory for both s1 and s2 pointers

char *s1=malloc(100*sizeof(char)), *s2=malloc(100*sizeof(char));
scanf("%99s",s1); //the "%99s" allow to avoid buffer overflow

And if you use gcc and your gcc>2.7 then you can use "%ms" in the scanf() in this way:

scanf("%ms",&s1);

with the "%ms", the scanf() will allocate memory for s1 pointer

2) and you have to add s-- in

while(*s++)
    ;
s--; // add s-- here
while(*s++ = *t++)
    ;

because the s pointer is pointing in the next element of '\0' element. the s pointer should be pointed in the '\0' element before starting copy the second string