Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computing length of array

Tags:

c++

arrays

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

CString carray[] =
{
        "A",
        "B",
        "C",
        "D",
        "E"
}

I want to determine the length of carray at runtime. I am doing:

int iLength = sizeof(carray)/sizeof(CString);

Is this correct?

like image 843
Ashish Ashu Avatar asked Jul 14 '09 10:07

Ashish Ashu


3 Answers

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.

like image 115
avakar Avatar answered Sep 23 '22 13:09

avakar


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

int iLength = sizeof(carray)/sizeof(carray[0]);
like image 17
Timbo Avatar answered Sep 24 '22 13:09

Timbo


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 
}
like image 6
David Rodríguez - dribeas Avatar answered Sep 24 '22 13:09

David Rodríguez - dribeas