【发布时间】:2019-01-07 13:29:47
【问题描述】:
我编写了一个函数,如果找到 'o',则将字符串“hello world”剪切为“hell”。
我不断收到分段错误。我不知道错误可能在哪里。 有人可以帮忙吗? 提前谢谢你。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* cutString(char* str, char del){
char *newstring =(char*) str;
malloc(sizeof(char)*strlen(str));
int i= 0;
for(; newstring[i]!='\0'&&newstring[i]!=del;i++);
if(i==strlen(newstring))
printf("not found");
else
newstring[i]='\0';
return newstring;
}
int main(){
cutString("Hello World",'o');
return 0;
}
【问题讨论】:
-
malloc(sizeof(char)*strlen(str));?您需要了解什么是返回值以及它们的含义。您正在使用该行代码创建一个内存块,然后将其丢弃,因为您不保存返回值。