Computing length of array

后端 未结 10 1279
萌比男神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:01

    Yes. In case the declared element type ever changes, you could also write

    int iLength = sizeof(carray)/sizeof(carray[0]);
    
    0 讨论(0)
  • 2020-12-19 14:01

    This code is correct but in most circumstances there are better ways to handle arrays in C++. Especially since this method won't work with dynamically sized arrays.

    For such cases, use the standard library class std::vector that represents an array of dynamic size (i.e. you can insert and remove entries).

    0 讨论(0)
  • 2020-12-19 14:02

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

    template <typename T, std::size_t N>
    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 
    }
    
    0 讨论(0)
  • 2020-12-19 14:04

    That's not runtime, it's compile time. The way you're using is correct. Note that Visual Studio defines a _countof function that does the same.

    At runtime, the length cannot be determined. You either keep a length yourself, or use std::vector

    0 讨论(0)
提交回复
热议问题