这道题查了很久的资料,最后还是找同学发现了问题。一开始是 char *a="I am a boy!"这样赋值的,这是一个字符串常量,其在程序中是存放在常量区的,其值是不能改变的。
一个已经犯了两次的错误。写在这记录下这个错误。
//反转句子中单词的顺序 2015.7.5
#include <stdio.h>
#include<string.h>
void ReverseWord(char* p, char* q) //单词两边对称交换
{
while(p < q)
{
char t = *p ;
*p++ = *q ;
*q-- = t ;
}
}
char * ReverseSentence(char *s) //使用字符指针,要考虑以‘\0结束的情况’
{
char *p = s ; // point to the first char of a word
char *q = s ; //after moved,point to a white space or '\0'
int n=strlen(s);
while(*q != '\0')
{
if (*q == ' ') //指针q一直自增,知道为第一个单词与第二个单词之间的空格
{
ReverseWord(p, q - 1) ; //调用这个函数后,指针q不在所期望的位置上
q++ ; // move to next word
p = q ;
}
else
q++ ;
}
//最后一个单词的情况,以‘\0’结束
ReverseWord(p, q - 1) ; // Reverse the last word
q=s+n-1; //指针q指向整个句子的结尾
ReverseWord(s, q ) ; // Reverse the whole sentence
return s ;
}
void main()
{
char a[]="I am a boy!";
char *b=ReverseSentence(a);
printf("%s",b);
//printf(ReverseSentence(a));
printf("\n");
}