I am writing a program that uses an array of pointers to strings str[].It receives two strings str1 and str2 and check if str1 is embedded in any of the strings in str[].If str1 is found, then replace it with str2. for example: if str1 contains "mountain" and str2 contains "car", then the second string in str should get changed to "Move a car" .When i try to execute this program , in gcc it is crashing,and when i tried to compile it online it is giving segmentation fault ,i am not able to understand where this program went wrong and what correction is needed in this.
#include<stdio.h>
#include<string.h>
char* xstrstr(char* ,char* );
int main()
{
char *str[]={
"We will teach you how to...",
"Move a mountain",
"Level a building",
"Erase the past",
"Make a million",
"...all through C!"
};
char* p, *temp, *cpy;
int len,i,j;
char str1[28];
char str2[10];
printf("Enter string1\n");
scanf("%s",str1);
printf("Enter string 2\n");
scanf("%s",str2);
printf("After modifying the saved strings\n\n");
for(i=0;i<6;i++)
{
p=xstrstr(str[i],str1);
if(p)
{
/*Copy the remaining string*/
temp=p+strlen(str1);
strcpy(cpy,temp);
/*Replace the old string*/
strcpy(p,str2);
/*Finally append the remaining part*/
strcat(p,cpy);
break;
}
}
if(p==NULL)
{
printf("No string match found\n");
return 1;
}
for(i=0;i<6;i++)
{
printf("%s\n",str[i]);
}
return 0;
}
char* xstrstr(char *string1,char* string2)
{
while(*string1)
{
char* begin=string1;
char* find=string2;
while((*string1)&&(*find)&&(*string1==*find))
{
string1++;
find++;
}
if(!(*find))
{
return begin;
}
string1=begin+1;
}
return NULL;
}