How to get the real and total length of char * (char array)?

前端 未结 15 2439
小蘑菇
小蘑菇 2020-11-29 00:37

For a char [], I can easily get its length by:

char a[] = \"aaaaa\";
int length = sizeof(a)/sizeof(char); // length=6

However,

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 01:15

    char *a = new char[10];

    My question is that how can I get the length of a char *

    It is very simply.:) It is enough to add only one statement

    size_t N = 10;
    char *a = new char[N];
    

    Now you can get the size of the allocated array

    std::cout << "The size is " << N << std::endl;
    

    Many mentioned here C standard function std::strlen. But it does not return the actual size of a character array. It returns only the size of stored string literal.

    The difference is the following. if to take your code snippet as an example

    char a[] = "aaaaa";
    int length = sizeof(a)/sizeof(char); // length=6
    

    then std::strlen( a ) will return 5 instead of 6 as in your code.

    So the conclusion is simple: if you need to dynamically allocate a character array consider usage of class std::string. It has methof size and its synonym length that allows to get the size of the array at any time.

    For example

    std::string s( "aaaaa" );
    
    std::cout << s.length() << std::endl;
    

    or

    std::string s;
    s.resize( 10 );
    
    std::cout << s.length() << std::endl;
    

提交回复
热议问题