-3

这是我的函数,应该将诸如“今天是美好的一天”之类的字符串翻转为“美好的一天是今天”我的 nextword 函数(在 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 回答