我是C编程的新手,曾尝试过一些简单的代码。下面的代码我有一个"分段错误",请帮忙。
代码如下:
#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 %sn",str);
}
else
{
printf("did not find the substrn");
}
return 0;
}
int del_substr(char *str,char const *substr)
{
int i=1;
char *temp=NULL;
while(*str!=' ')
{
if(*str==*substr)
{
while(*(substr+i)!=' ' && *(substr+i)==*(str+i))
{
i++;
}
if(*(substr+i)==' ')
{
printf("We find it!n");
temp=str;
}
}
if(temp!=NULL)
{
break;
}
else
{
str++;
i=1;
}
}
if(temp!=NULL)
{
while(*(temp+i)!=' ')
{
*temp=*(temp+i);
temp++;
}
*temp=' ';
return 1;
}
else
{
return 0;
}
}
这段代码的目的是在str中找到substr,然后从str中删除substr,将substr后面的所有内容向前移动,返回1。否则,如果搜索失败,则返回0。
当代码运行到下面的行时,就会出现分段错误。
*temp=*(temp+i);
有人能帮忙吗?提前非常感谢。
谢谢。
您不能在'C'中修改文字字符串。
尝试更换
char *str="welcome";
char *substr="com";
带有
char str[]="welcome";
char substr[]="com";