c 语言高手请进 帮我看看这两个c程序

来源:百度知道 编辑:UC知道 时间:2024/05/28 16:07:45
int fun (char*s)
{char *t=s;
while (*t++);
return(t-s);
这是个选择题的题干 答案写的是改程序的功能是计算s所指字符串的长度

另一个程序
int fun (char*s)
{char *t=s;
while (*t++);
t--;
return(t-s);
此功能是求字符串s的长度 为什么两个程序不一样 功能都一样呢

前面的程序是错的,多算了1个
后面的才是对的;
关键在while (*t++);
当*t=='\0'时,t还是加了

不妨看测试程序:
#include <stdio.h>
int fun1(char*s)
{char *t=s;
while (*t++);
return(t-s);
}
int fun2(char*s)
{char *t=s;
while (*t++);
t--;
return(t-s);
}

void main()
{
char *p="abcd";
printf("fun1=%d\n",fun1(p));
printf("fun2=%d\n",fun2(p));
}

输出结果
fun1=5
fun2=4

实际上,第一函数求的字符串的真正的长度,它把字符串结尾的0也就算进去了,第二函数计算的是实际意义的长度,不考虑结尾的0