C++中数组strlen
黄舟
黄舟 2017-04-17 15:04:59
[C++讨论组]
char a[] = {'a','b','c'};
cout << strlen(a) << endl;
输出 6

char a[3] = {'a','b','c'};
cout << strlen(a) << endl;
输出 6

char a[4] = {'a','b','c'};
cout << strlen(a) << endl;
输出 3

strlen 会一直往前找直到找到'\0',但是为什么第一第二个会返回 6 呢?
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(4)
迷茫

对无 \0 结尾的字符串调用 strlen 是未定义行为。

怪我咯

先分析您的代码:

char a[] = {'a','b','c'}; // 请问什么时候结束?  strlen找不到空字符, 所以结果错误.
cout << strlen(a) << endl;
输出 6

char a[3] = {'a','b','c'}; // 同上
cout << strlen(a) << endl;
输出 6

char a[4] = {'a','b','c'}; // 有默认初始化, char a[4] = {'a','b','c', '\0' }; 所以结果是对的
cout << strlen(a) << endl;
输出 3

进一步理解

#include <iostream>
#include <cstring>
using namespace std;

int main(int argc, char **argv)
{
    char a[]={'a','b','c'};
    cout << "char a[] = " << strlen(a) << endl;

    char b[]={'a','b','c','\0'};
    cout << "char b[] = " << strlen(b) << endl;

    char pa[] = "abc";
    cout << "char *pa = " << strlen(pa) << endl;

    char pb[20] = "abc";
    cout << "char *pb = " << strlen(pb) << endl;
    return 0;
}
$ ./a.exe
char a[] = 4
char b[] = 3
char *pa = 3
char *pb = 3

strlen 说明

Get string length

Returns the length of the C string str.

The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string";

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

ringa_lee

字符数组是字符数组,字符串是字符串。只有字符串才有 \0,字符数组没这待遇。这三个代码片段输出的结果,应该都是随机值——恰好从 a 开始偏移的那段内存中有个数据让 strlen 误认为是 \0,于是它就返回了自己读到的字节数。

被踩了一下……可能踩我的人认为,当数组的长度大于字符串实际长度时,编译器会自动在字符串末尾添加 \0。事实上,这依赖于编译器的具体实现,C 标准中对此没有什么说法。

高洛峰
楼上的几位直接告诉楼主, 数组永远不要用strlen不行吗, 严谨的写法 sizeof(arr) / sizeof(type)
即: sizeof(a)/sizeof(char)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号