int funl(char *x)
{ char *y=x;
while(*y++);
return(y-x-1);《===怎么计算的??
}
int funl(char *x)
{ char *y=x;
while(*y++);
return(y-x-1);《===怎么计算的??
}
int funl(char *x)
{ char *y=x; //Sent the first adr
while(*y++); //move by step till '*y == NULL'
return(y-x-1); //The last adr sub the first adr
//and sub '1' is equal to the length
//of the string 'x' or string 'y'
}
int fun1(char *x)
{
char *y=x;
while(*y++);
return(y-x-1);
}
#include<stdio.h>
main()
{
char s[]="1234567890";
printf("%d\n",fun1(s));
}
//运行结果:10
//由此可见:fun1()测试串长度
int funl(char *x)
{ char *y=x; // 这里存放了x的首地址
while(*y++); //这个循环当*y不为字符处结束符(即'\0')时执行循环,而且每次循环指针往后挪了,那么这个循环结束就是y的尾地址(也就是x的尾地址)。
return(y-x-1);《===怎么计算的??
y - x - 1 就是xn - x0 - 1(xn表示x的尾地址,x0表示x的首地址)这样减下来不就是x这个字符串的长度-1吗? }
不好意思纠正一下我在六楼的回答,当*y遇到0时退出循环之前y又加了一次,这样y - x - 1就返回了字符串本身的长度。
这里循环结束的时候,y指针指向了字符串结尾标志\0得下一个标志(乱码);
所以字符串长度应该世结尾指针(y-1)减去头指针(x);
现在明白了吧;
good good study ,day day up
[此贴子已经被作者于2006-6-11 16:04:15编辑过]