我一直收到这个错误,我不确定它如何适用于我的程序。这是我的程序。
#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!!
发布于 2012-10-02 06:46:47
您正在尝试更改String literal。这会导致未定义的行为,例如段错误。
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"
是字符串文字更改,它是未定义的行为,在您的示例中(幸运的是)它导致了seg-fault。
发布于 2012-10-02 06:45:21
你应该启用所有警告和调试信息进行编译(如果使用的是GCC,例如在Linux上,这意味着使用gcc -Wall -g
进行编译)。
然后,您应该学习如何使用调试器(即Linux上的gdb
),可能还会使用像valgrind这样的泄漏检测器。
如果你取消引用一些“坏的”指针,例如一个空指针或一个未初始化的指针,就可能发生segmentation fault。如果你写到一个只读段中,也可能会发生这种情况(你可能正在覆盖一个字符串文字,它被放入一个称为.text
或.rodata
- -so的只读段中)。
考虑到编译器的每一个警告(并启用它们)并使用调试器是任何C程序员的基本技能。
发布于 2012-10-02 06:49:13
请给nextindex
一个初始值
https://stackoverflow.com/questions/12685600
复制