Computing length of array

后端 未结 10 1278
萌比男神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 13:47

    The best way is to use a macro and use that where ever you want the size.

    #define MAX_ROWS 1048
    int array[MAX_ROWS];
    

    This way you can use the MAX_ROWS even in a function where the array is passed as an argument.

    0 讨论(0)
  • 2020-12-19 13:48

    Windows SDK (i.e. windows.h header) offers the macro ARRAYSIZE which implements this functionality in a safe manner(i.e. doesn't work with non-static arrays)

    0 讨论(0)
  • 2020-12-19 13:49

    Read this article by Ivan J. Johnson in Dr. Dobbs Journal. I think it covers most of the solutions presented here. It also outlines the merits and demerits of each approach very nicely.

    0 讨论(0)
  • 2020-12-19 13:53

    Yes, this is the correct way to do it, but it will only work in this situation where the size of array is known at compile time and is seen at the site of the sizeof( array ) statement. It will not work with dynamically sized arrays - you will need other methods for them like using a container like stl::vector or passing/storing the number of elements as a separate parameter.

    0 讨论(0)
  • 2020-12-19 13:57

    You can use the following function template. If you're using Boost, you can call boost::size.

    template <typename T, std::size_t N>
    std::size_t size(T (&)[N])
    {
        return N;
    }
    
    int iLength = size(carray);
    

    As others have already stated, however, you should prefer std::vector to C-style arrays.

    0 讨论(0)
  • 2020-12-19 13:57

    If you have a dynamic array, you should probably use something like an STL vector. http://www.cppreference.com/wiki/stl/vector/start

    Normal arrays in C++ are fixed size and you need to manually allocate memory to expand dynamic ones.

    If you know your array size at compile time, use a constant rather than a calculation.

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