注册 登录
编程论坛 C++教室

关于strlen()

zzt_428 发布于 2008-09-13 15:42, 885 次点击
本人有些概念搞不清楚,做了个小的测试,程序如下:
#include <iostream>
using namespace std;

int main()
{
    const char *s="China!";
    char arr[6]={'C','h','i','n','a','!'};
    cout << strlen(s) << endl;          //output:6
    cout << strlen("China!") << endl;   //output:6

    cout << strlen(arr) << endl;     // output : 11
     
    return 0;
}

如果把char arr[6]={'C','h','i','n','a','!'};改为char arr[6]={'C','h','i','n','a'};那么长度就是5了,哪位能解释一下,这是为什么?为什么就多了一个数组元素,长度就增加了那么多?
哪位知道的,希望能帮我字符串指针,数组名, 字符串的长度的概念给我澄清一下,,谢谢!
8 回复
#2
ma35872008-09-13 16:17
而strlen函数是查找到字符串结束字符‘\0‘结束,所以strlen(ch)有可能等于任何值,这取决于你的编译器。
#3
blueboy820062008-09-13 17:08
你试一下这几句:
char arr[7]={'C','h','i','n','a','!'};
char arr[7]={'C','h','i','n','a','!','!'};
char arr[8]={'C','h','i','n','a','!','!','!'};

有意思...
#4
zzt_4282008-09-13 17:27
谢谢楼上的,明白了!呵呵呵呵
#5
newyj2008-09-13 19:56
strlen是c类型的 所以要检查'\0'
而char arr[6]={'C','h','i','n','a','!'};没有提供'\0'所以并不能取得比较确切的值
因为 它要在找那个'\0'
#6
liotta2008-09-13 20:19
数组arr没有添加'\0',不能使用string类函数,结果未知!
属常现错误。
#7
kevin882008-10-02 02:13
回复 3# blueboy82006 的帖子
是数组长度太短了吧
#8
守鹤2008-10-02 12:39
注意字符数组与字符串数组的区别,

strlen()是处理字符串的函数
#9
kevin882008-10-02 18:58
char arr[6]={'C','h','i','n','a','!'};
好像放不下/0了
1