当我运行我的程序时,我不断收到错误分段错误(核心转储)。
#include<stdio.h>
#include<stdlib.h>
int nextword(char *str);
int main(void)
{
char str[] = "Hello! Today is a beautiful day!!\t\n";
int i = nextword(str);
while(i != -1)
{
printf("%s\n",&(str[i]));
i = nextword(NULL);
}
return 0;
}
int nextword(char *str)
{
// create two static variables - these stay around across calls
static char *s;
static int nextindex;
int thisindex;
// reset the static variables
if (str != NULL)
{
s = str;
thisindex = 0;
// TODO: advance this index past any leading spaces
while (s[thisindex]=='\n' || s[thisindex]=='\t' || s[thisindex]==' ' )
thisindex++;
}
else
{
// set the return value to be the nextindex
thisindex = nextindex;
}
// if we aren't done with the string...
if (thisindex != -1)
{
nextindex = thisindex;
// TODO: two things
// 1: place a '\0' after the current word
// 2: advance nextindex to the beginning
// of the next word
while (s[nextindex] != ' ' && s[nextindex] != '\0')
nextindex++;
str[nextindex] = '\0';
nextindex++;
}
return thisindex;
}
该程序的目标是将字符串 str[] 中的每个单词打印到控制台的新行。我是一个初级程序员,这是一个作业,所以我必须使用这种格式(不允许字符串库)。我只是想知道我哪里出了问题以及如何解决它。