Hello Everyone, I got this question in some book. As per question we need to find a substring in a array of char* and replace it with another string. The program I wrote doesn't work. I tried using strcpy as well char by char. Please help me to figure out if it's me or the question is wrong.
I know "char ptr" is "ptr to const" so we can't modify the string it points to
Thanks a lot!
#include<stdio.h>
#include<string.h>
int main()
{
char * arr[] = { "We will teach you how to",
"Move a mountain",
"Level a building",
"Erase the past",
"Make a million",
"All through C!"
};
char arr1[10]="mountain";
char arr2[10]="car";
char* found= NULL;
int i;
printf("arr1= %s will be replaced by arr2= %s in arr\n",arr1,arr2);
for(i=0;i<6;i++)
{
found = strstr(arr[i],arr1);
if(found)
{
strcpy(found,arr2); // **Segmentation Fault**
}
found= NULL;
}
return 0;
}
/* Another Version of that condition, char by char
if(found)
{
for(j=0;arr2[j]!='\0';j++)
{
*found = arr2[j];
++found;
}
*found='\0';
}
*/