使用指针反转字符串

我正在尝试使用指针来反转一个字符串。当我尝试打印反向字符串而不是获得DCBA时,我只是作为BA出来?有人可以帮我这个吗?

#include void reverse(char *); void main() { char str[5] = "ABCD"; reverse(str); } void reverse(char *str) { char *rev_str = str; char temp; while(*str) str++; --str; while(rev_str < str) { temp = *rev_str; *rev_str = *str; *str = temp; rev_str++; str--; } printf("reversed string is %s",str); } 

你丢失了指向字符串开头的指针,所以当你打印它时,你不会从第一个字符开始,因为str不再指向第一个字符。 只需放入一个占位符变量来保持指向字符串开头的指针。

 void reverse(char *str) { char *begin = str; /* Keeps a pointer to the beginning of str */ char *rev_str = str; char temp; while(*str) str++; --str; while(rev_str < str) { temp = *rev_str; *rev_str = *str; *str = temp; rev_str++; str--; } printf("reversed string is %s\n", begin); } 
 char* strrev(chr* src) { char* dest int len=0, index=0 , rindex=0; while(*(src+len) != '\0') { len++ } rindex=len-1; while(rindex > =0) { *(dest+index) = *(src + rindex) index++; rindex--; } *(dest+index) = '\0'; return dest; }