首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

strlen()求解解决方法

2012-03-31 
strlen()求解我用strlen()求一个字符数组长度,这个字符数组全是数字,我是这样设置数组值:1,1,1,1,0,0.....

strlen()求解
我用strlen()求一个字符数组长度,这个字符数组全是数字,我是这样设置数组值:1,1,1,1,0,0.......
使用strlen()求这个数组返回的是4.为什么???

[解决办法]
因为它的实现是这样子的:

C/C++ code
size_t __cdecl strlen (        const char * str        ){        const char *eos = str;        while( *eos++ ) ;        return( eos - str - 1 );}
[解决办法]
c语言字符串以‘\0’为结束符,也就是数字0。
[解决办法]
strlen() 是用来测试char 数组的 遇到结束标记\0就结束,你用来测试int 数组,因为\0=0 所以就出现你那种情况,例如 1,1,1,1,0,1,1,1, 同样结果也是4
[解决办法]
1、需要明白strlen是判断字符长度,字符里0表示'\0'结束符,如果需要存放数字需要转换。
2、如果是整型数组或指针指向的内存,不建议用strlen进行判断,可以用sizeof
[解决办法]
因为 strlen() 以碰到 '\0'或 0 或 NULL(不过 NULL 会有警告^_^) 更或是 NUL 作为结束条件并且不将它计算在内!

楼上是他的源码!

贴一段英语一块儿学习: 
C/C++ code
NULL is a macro defined in several standard headers, 0 is an integer constant, '\0' is a character constant, and nul is the name of the character constant. All of these are not interchangeable:NULL is to be used for pointers only since it may be defined as ((void *)0), this would cause problems with anything but pointers.0 can be used anywhere, it is the generic symbol for each type's zero value and the compiler will sort things out.'\0' should be used only in a character context.nul is not defined in C or C++, it shouldn't be used unless you define it yourself in a suitable manner, like:#define nul '\0' 

热点排行