-3

これは、「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);
}
4

2 に答える 2

2

printf("%s\n",buf[0]);セグメンテーション違反を引き起こす文字列の代わりに文字を printf に渡しています。printf("%s\n", buf);代わりに使用してください。

また、単語を正しくコピーしていませんbuf[c]=str[i[j]+c];。c では、現在の単語の先頭からのオフセットではありませんが、buf の先頭からオフセットとして使用するには、別のカウンターを使用する必要があります。

l = 0;
while(buf[c]!='\0'){
   c++;
   l++;
   buf[c]=str[i[j]+l];
}
于 2012-10-05T06:15:17.363 に答える
0

この指示を確認してください:

buf[c]=str[i[j]+c];

c は、関数の最初で 0 に初期化されるカウンターであり、このカウンターを使用して buf の位置を設定し、str の位置を設定しています。この命令は奇妙で、セグメンテーション違反を引き起こす可能性があります。

2 つの異なるカウンターを使用してみてください。1 つは buf 用で、もう 1 つは str 用です。

于 2012-10-05T06:18:42.313 に答える