Computing length of array

后端 未结 10 1311
萌比男神i
萌比男神i 2020-12-19 13:37

I have a C++ array declared as mentioned below:

CString carray[] =
{
        \"A\",
        \"B\",
        \"C\",
        \"D\",
        \"E\"
}
10条回答
  •  被撕碎了的回忆
    2020-12-19 14:02

    That is correct, as it is using metaprogramming as this:

    template 
    inline std::size_t array_size( T (&)[N] ) {
       return N;
    };
    

    You must know that this works when the compiler is seeing the array definition, but not after it has been passed to a function (where it decays into a pointer):

    void f( int array[] )
    {
       //std::cout << array_size( array ) << std::endl; // fails, at this point array is a pointer
       std::cout << sizeof(array)/sizeof(array[0]) << std::endl; // fails: sizeof(int*)/sizeof(int)
    }
    int main()
    {
       int array[] = { 1, 2, 3, 4, 5 };
       f( array );
       std::cout << array_size( array ) << std::endl; // 5
       std::cout << sizeof(array)/sizeof(array[0]) << std::endl; // 5 
    }
    

提交回复
热议问题