Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...