且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sizeof(array)/sizeof(array [0])有什么问题吗?

更新时间:2023-01-27 09:18:28

也许您的同事意味着将这个表达式与指针一起使用会产生意想不到的结果.初学者经常犯此错误.例如

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;
}

请考虑到C ++ 11中存在模板结构std::extent,可用于获取尺寸大小.

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

例如

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;