sizeof(array)/sizeof(array[0])有什么问题吗? [英] Is there anything wrong with sizeof(array)/sizeof(array[0])?

查看:73
本文介绍了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.

虽然我同意类型安全,但我有点困惑,因为这是有问题的代码类型(仅修改了 data[] 的内容和长度)

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:这用于将初始化数据从构造函数复制到类中,此处不存在 C++11 编译器,因此我们不能使用 std::array 或其他花哨的数组初始化.技术.

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.

推荐答案

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

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;

这篇关于sizeof(array)/sizeof(array[0])有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆