我是C的新手,我应该创建strtok函数。问题是,我在这段代码中不断收到分段错误错误:
char *newstring = "testing, testing, tested."
while(*newstring != '\0' ){
/*replace delimiters with nulls*/
printf("STARTING ITERATION\n");
if(*newstring ==','){
*newstring='\0';
}
printf("newstring char in loop: %c\n", *newstring);
/*printf("delimiters char in loop: %c\n", *delimiters);*/
newstring++;
printf("END OF ITERATION\n");
}
printf("OUT OF ITERATION");
因此输出:
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop: e
END OF ITERATION
STARTING ITERATION
newstring char in loop: s
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop:
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop: e
END OF ITERATION
STARTING ITERATION
newstring char in loop: s
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop:
END OF ITERATION
STARTING ITERATION
newstring char in loop: t
END OF ITERATION
STARTING ITERATION
newstring char in loop: e
END OF ITERATION
STARTING ITERATION
newstring char in loop: s
END OF ITERATION
STARTING ITERATION
newstring char in loop: .
END OF ITERATION
Segmentation fault (core dumped)
所以,看起来它一直到字符串的结尾和循环的结尾,但实际上并没有使它成为循环的结果。我不确定我错过了什么。
答案 0 :(得分:3)
您正在尝试修改C中不允许的字符串文字。如果您将char *newstring = "testing, testing, tested."
更改为char newstring[] = "testing, testing, tested."
,那么您正在修改数组的内容。