-1

Here i'm trying to replace the word "how are you" in string array 's' by "woo". But it is exiting abruptly during the runtime . please help

char *s[] = {"hi there","how are you","Fine Ok!"};
char str1[4] = "how" ;char str2[4] = "woo";
char *j = NULL; //(char *)malloc(100*sizeof(char));
int i,k; char n[100] = "hi";
//printf("%d",strlen(s));
for(i = 0;i<3;i++ )
{
    j = strstr(s[i],str1);
    if(j==0)
    continue;
    else
    {
        printf("j is %s",j);
        printf("j is %s",j+10);
        strcpy(j,str2);

        printf("j is %s",j);
        break;
    }
}
printf("%s",s[1]);
return 0;
naiveBayes
  • 35
  • 1
  • 8

1 Answers1

2

You have multiple problems in your code. Lets start with one of the more obvious: Remember that strcpy adds the string terminator. You might want to use memcpy instead:

memcpy(j, str2, strlen(str2));

To continue, you allocate memory and assign it to j, then in the loop you reassign to j making j point somewhere else, and you loose the original memory you have allocated leading to a memory leak. Also, in C you should not cast the result of malloc.

Lastly, and the probable cause of your crash: You try to modify a string literal, and all string literals are read only.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621