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

查看:159
本文介绍了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天全站免登陆