我一直收到这个错误,我不确定它如何适用于我的程序。这是我的节目。

#include<stdio.h>
#include<stdlib.h>

int nextword(char *str);



void 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);
    }
}

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] != '\n' || s[nextindex] != '\t')
    {
      if ( s[nextindex] == '\0')
        return -1;
      else
        {
          nextindex++;
          if (s[nextindex]==' '||s[nextindex]=='\n'||s[nextindex]=='\t')
        str[nextindex]='\0';
        }
    }

    }
  return thisindex;
}

我的程序应该有一个输出到控制台
Hello!
Today
is
a
beautiful
day!!

最佳答案

您正在尝试更改aString literal。这会导致未定义的行为,例如segfault。

str[nextindex]='\0'

这里,strnextWord()的参数,它是:
char *str = "Hello! Today is a beautiful day!!\t\n";
int i = nextword(str);

因为"Hello! Today is a beautiful day!!\t\n"是一个字符串文字更改,所以它是udnefined行为,在您的情况下(幸运的是),它导致了seg错误。

09-20 02:07