c++ strlen 与 sizeof

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

int main(void)
{
    char arr[4];
    cout<<"--->"<<endl;
    cout<< "arr 4 len : "<< strlen(arr)<<endl;
    cout<< "arr 4 len : "<< sizeof(arr)<<endl;
    arr[0]='a';
    arr[1]='a';
    cout<<"--->"<<endl;
    cout<< "arr 4 len : "<< strlen(arr)<<endl;
    cout<< "arr 4 len : "<< sizeof(arr)<<endl;
    arr[2]='a';
    cout<<"--->"<<endl;
    cout<< "arr 4 len : "<< strlen(arr)<<endl;
    cout<< "arr 4 len : "<< sizeof(arr)<<endl;
    arr[3]='a';
    cout<<"--->"<<endl;
    cout<< "arr 4 len : "<< strlen(arr)<<endl;
    cout<< "arr 4 len : "<< sizeof(arr)<<endl;

    arr[4]='\0';
    cout<<"--->"<<endl;
    cout<< "arr 4 len : "<< strlen(arr)<<endl;
    cout<< "arr 4 len : "<< sizeof(arr)<<endl;

    return 0;
}

--->
arr 4 len : 0
arr 4 len : 4
--->
arr 4 len : 2
arr 4 len : 4
--->
arr 4 len : 3
arr 4 len : 4
--->
arr 4 len : 10
arr 4 len : 4
--->
arr 4 len : 4
arr 4 len : 4

由于给 arr[3]赋值,覆盖了原来的’\0′,导致系统自动计算到下个碰到的’\0′

std::strlen

返回给定字节字符串的长度,即字符数组中的字符数,该字符数组的第一个元素由str直到并且不包括第一个空字符。如果指向的字符数组中没有空字符,则该行为是未定义的

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.