Search code examples
c++arraystype-safety

Is there anything wrong with sizeof(array)/sizeof(array[0])?


One of my colleagues has recently said that the above statement is not type safe and I should use something else as you need as much type safe structures as possible to reduce the amount of possible bugs.

Whilst I agree on being type safe, I'm a little confused as this is the type of code in question (only the contents and length of data[] is modified)

unsigned char data[] = {1,2,3,4,5};
int data_len = sizeof(data) / sizeof(data[0]); 

Where is the part that is not type safe?

Needless to say, other than the comment, the colleague will not explain further.

PS: This is used to copy initialisation data into a class from the constructor, no C++11 compiler exists here, so we can't use std::array or other fancy array initialisation. techniques.


Solution

  • Maybe your colleague meant that using this expression with pointers will give an unexpected result. This mistake is made very often by beginners. For example

    void f( unsigned char data[] )
    {
       int data_len = sizeof(data) / sizeof(data[0]); 
       //...
    }
    
    //...
    
    unsigned char data[] = {1,2,3,4,5};
    f( data );
    

    So in general case it would be more safely to use a template function instead of the expression. For example

    template <class T, size_t N>
    
    inline size_t size( const T ( & )[N] )
    {
       return N;
    }
    

    Take into account that there is template structure std::extent in C++ 11 that can be used to get the size of a dimension.

    For example

    int a[2][4][6];
    
    std::cout << std::extent<decltype( a )>::value << std::endl;
    std::cout << std::extent<decltype( a ), 1>::value << std::endl;
    std::cout << std::extent<decltype( a ), 2>::value << std::endl;