recherche

Maison  >  Questions et réponses  >  le corps du texte

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 呢?
黄舟黄舟2803 Il y a quelques jours554

répondre à tous(4)je répondrai

  • 迷茫

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

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

    répondre
    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', '\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.

    répondre
    0
  • ringa_lee

    ringa_lee2017-04-17 15:06:59

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

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

    répondre
    0
  • 高洛峰

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

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

    répondre
    0
  • Annulerrépondre