C++中数组strlen
黄舟
黄舟 2017-04-17 15:04:59
0
4
526
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 呢?
黄舟
黄舟

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

reply all(4)
迷茫

Yes None

刘奇

先分析您的代码:

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', '
#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','
$ ./a.exe
char a[] = 4
char b[] = 3
char *pa = 3
char *pb = 3
'}; 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; }
' }; 所以结果是对的 cout << strlen(a) << endl; 输出 3

进一步理解

rrreee rrreee

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.

左手右手慢动作

Character array is a character array and string is a string. Only strings have

I was downvoted... The person who downvoted me may think that when the length of the array is greater than the actual length of the string, the compiler will automatically add
小葫芦
楼上的几位直接告诉楼主, 数组永远不要用strlen不行吗, 严谨的写法 sizeof(arr) / sizeof(type)
即: sizeof(a)/sizeof(char)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!