将字符串逆置

来源:百度知道 编辑:UC知道 时间:2024/06/17 04:07:15
#include <string.h>
#include <conio.h>
#include <stdio.h>
#define N 81

void fun ( char *s)
{
int i,j=0,n=strlen(s);
for(i=n-1;i>=0;i--)
s[j++]=s[i];
s[j]='\0';
}

main()
{
char a[N];
FILE *out;
printf ( "Enter a string : ");
gets ( a );
printf ( "The original string is: " );
puts( a );
fun ( a );
printf("\n");
printf ( "The string after modified : ");
puts ( a );
strcpy(a, "Hello World!");
fun(a);
out = fopen("out.dat", "w");
fprintf(out, "%s" , a);
fclose(out);
}
为什么以上的程序是错误的?说明下理由?

void fun ( char *s)
{
int i,j=0,n=strlen(s);
for(i=n-1;i>=0;i--) //i>=int(N/2);
s[j++]=s[i]; //前一段被后一段代替了。将上面i>=0;改成如上就好了
s[j]='\0';
}