Home  >  Q&A  >  body text

C++中数组strlen

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 呢?
黄舟黄舟2713 days ago505

reply all(4)I'll reply

  • 迷茫

    迷茫2017-04-17 15:06:59

    Yes None

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:06:59

    先分析您的代码:

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 15:06:59

    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

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:06:59

    楼上的几位直接告诉楼主, 数组永远不要用strlen不行吗, 严谨的写法 sizeof(arr) / sizeof(type)
    即: sizeof(a)/sizeof(char)
    

    reply
    0
  • Cancelreply