Search code examples
c++arrayscharsizeofsize-t

how to get a length of char array char*


i have something like this char * array[] = {"one","two","three","five"}; how can I get its length (which is 3 here). if I use strlen() then I get the length of "one".


Solution

  • For starters you have to use the qualifier const in the array declaration.

    const char * array[] = {"one","two","three","five"};
    

    To get the number of elements in the array you can write

    size_t n = sizeof( array ) / sizeof( *array );
    

    If your compiler supports the C++ 17 Standard then you also can write

    #include <iterator>
    
    //...
    
    size_t n = std::size( array );
    

    Before the C++ 17 Standard you can use the structure std::extent.

    For example

    #include <type_trats>
    
    //...
    
    size_t n = std::extent<decltype( array )>::value;