I am new to C programming and was try on some simple code. I got a "segmentation fault" for below code, please help.
The code as below:
#include <stdio.h>
int del_substr(char *str,char const *substr);
int main(void)
{
char *str="welcome";
char *substr="com";
int result;
result=del_substr(str,substr);
if(result==1)
{
printf("find and deleted! new string is %s\n",str);
}
else
{
printf("did not find the substr\n");
}
return 0;
}
int del_substr(char *str,char const *substr)
{
int i=1;
char *temp=NULL;
while(*str!='\0')
{
if(*str==*substr)
{
while(*(substr+i)!='\0' && *(substr+i)==*(str+i))
{
i++;
}
if(*(substr+i)=='\0')
{
printf("We find it!\n");
temp=str;
}
}
if(temp!=NULL)
{
break;
}
else
{
str++;
i=1;
}
}
if(temp!=NULL)
{
while(*(temp+i)!='\0')
{
*temp=*(temp+i);
temp++;
}
*temp='\0';
return 1;
}
else
{
return 0;
}
}
This code is meant to find substr in str and then delete substr from str, moving everything behind substr forward, return 1. else if failed in the searching, return 0 instead.
when the code runs to below line, a segmentation fault is showing up.
*temp=*(temp+i);
Can anyone help? Thanks so much in advance.
Thanks.