我试图通过插入空字符在C中拆分字符串,并且我不断收到错误segmentation fault (core dumped).
行p[0] = '\0'
;一直造成这个问题。如何通过在"say hello?
“
char *sentence = "say hello";
printf("You typed: %s\n", sentence);
char *allbutfirst = sentence + 1;
printf("Everythign but first letter is %s\n", allbutfirst);
char *secondpart = sentence + 5;
printf("Skipping the first 5 letters, the rest is %s\n", secondpart);
// strchr finds the first occurence of a letter
char *p = strchr(sentence, ' ');
printf("Everythign starting at first space is %s\n", p);
// turn the space into a '\0' "null character", effectively splitting
// the string into two parts.
p[0] = '\0'; // assign using array notation
// now, sentence ends where the space used to be
// and (p+1) points to the rest of the text.
printf("First word is %s\n", sentence);
printf("Rest of sentence is %s\n", p + 1);
答案 0 :(得分:1)
这是因为
char *sentence = "say hello";
应该实际声明为
const char *sentence = "say hello";
字符串文字,即用"say hello"
等引号编写的代码中的字符串文字
不可变,意味着它们是只读的,你不能改变它们的内容。
char *p = strchr(sentence, ' ');
如果找到空白区域,p
仍然指向只读内存,因此
p[0] = '\0';
以段错结束。如果空白区域,strchr
也可以返回NULL
找到不,当p
为NULL
时,这也会导致段错误。
如何解决?使用char
数组,并使用字符串初始化它,
还要检查strchr
的返回值:
#include <stdio.h>
#include <string.h>
int main(void)
{
char sentence[] = "say hello";
printf("You typed: %s\n", sentence);
char *allbutfirst = sentence + 1;
printf("Everythign but first letter is %s\n", allbutfirst);
char *secondpart = sentence + 5;
printf("Skipping the first 5 letters, the rest is %s\n", secondpart);
// strchr finds the first occurence of a letter
char *p = strchr(sentence, ' ');
if(p == NULL)
{
fprintf(stderr, "Empty space not found\n");
return 1;
}
printf("Everythign starting at first space is %s\n", p);
// turn the space into a '\0' "null character", effectively splitting
// the string into two parts.
p[0] = '\0'; // assign using array notation
// now, sentence ends where the space used to be
// and (p+1) points to the rest of the text.
printf("First word is %s\n", sentence);
printf("Rest of sentence is %s\n", p + 1);
return 0;
}