0

我不断收到此错误,我不确定它如何应用于我的程序。这是我的程序。

#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!!
4

3 回答 3

5

您正在尝试更改String 文字。这会导致未定义的行为,例如段错误。

str[nextindex]='\0'

在这里,str是 的参数nextWord(),即:

char *str = "Hello! Today is a beautiful day!!\t\n";
int i = nextword(str);

因为"Hello! Today is a beautiful day!!\t\n"是字符串文字 - 更改它是未定义的行为,并且在您的情况下(幸运的是)它导致了段错误。

于 2012-10-02T06:46:46.790 回答
4

您应该在启用所有警告和调试信息的情况下进行编译(如果在 Linux 上使用GCC,则意味着使用 编译gcc -Wall -g)。

然后你应该学习如何使用调试器(即gdb在 Linux 上)和可能的泄漏检测器,如valgrind

如果您取消引用一些“坏”指针,例如 NULL 指针或未初始化指针,则可能会发生分段错误。如果您写入只读段,也可能发生这种情况(您可能正在覆盖放入只读段的字符串.text文字.rodata

考虑编译器的每个警告(并启用它们)并使用调试器是任何 C 程序员的基本技能。

于 2012-10-02T06:45:21.323 回答
0

请给nextindex一个初始值

于 2012-10-02T06:49:13.180 回答