C语言代码疑问

来源:百度知道 编辑:UC知道 时间:2024/05/26 19:54:42
1.int z(char s[])
{
char t;
int n,i,j;
n=strlen(s);

for(i=0;i<=n/2;i++,n--)
{
t=s[i];
s[i]=s[n-1];
s[n-1]=t;
}
}
2.int z(char s[])
{
char t;
int n,i,j;
n=strlen(s);

for(i=0;i<=n/2;i++)
{
t=s[i];
s[i]=s[n-i];
s[n-i]=t;
}
}
我觉得这2个函数效果应该相同,为什么前者可运行 而后者 运行后什么都没?

s[i]=s[n-i]; 这里有问题,数组访问越界,当i=0时,n-0即n,而数组的下标从0 - n-1。

这两个函数结果肯定不一样,第一个函数的循环条件时刻在变,因为n在减小;第二个函数的循环条件不会变