これは、「Today isabeautifulday」などの文字列を「daybeautifulaisToday」に反転することになっている関数です。次の単語関数(flipstring関数内)は、文字列内のすべての単語の先頭のインデックスを返します。単語の後に「\0」を配置します。この関数を使用すると、エラー、セグメンテーション違反(コアダンプ)が発生し、その理由がわかりません。
void flip(char *str)
{
// reverse the order of the words
char buf[256];
int i[2],k,j=0,c=0;
//set k to the index of the first word in str
k = nextword(str);
//Create an array (i) of the index of the beginning of every word
//nextword also places a '\0' after every word in str
while ( k != -1)
{
i[j] = k;
j++;
k = nextword(NULL);
}
//place each word in buf in reverse order
//replace the eos with a space
for ( j=j-1 ; j >= 0 ; j--) //starts with index of last word in string str
{
buf[c]=str[i[j]];
while(buf[c]!='\0')
{
c++;
buf[c]=str[i[j]+c];
}
buf[c] = ' '; //replaces '\0' after every word with a space
c=c+1;
}
buf[c] = '\0'; //Places eos at the end of the string in buf
printf("%s\n",buf[0]);
}
あれを呼べ、
void main(void)
{
char str[] = "Today is a beautiful day!\t\n";
flip(str);
//printf("%s",str);
}