使用 sizeof() 计算数组大小
Calculation of Array size using sizeof()
摘自 TopCoder article:
The expression sizeof(data)/sizeof(data[0])
returns the size of the array data
, but only in a few cases, so don’t use it anywhere except in such constructions.(C programmers will agree with me!)
为了获得数组大小,我一直在对所有基本类型.
使用这个表达式sizeof(data)/sizeof(data[0])
有人知道上面的表达式 不应该 的任何情况吗?
如果 data
是这样声明的:
int *data;
然后 space 分配如下:
data = malloc( NUM_ELEMENTS * sizeof(int) );
那你的技术就不行了,因为sizeof(data)
是指针的大小,不是数组的内容。
sizeof
方法可以编译,但在给它一个指针或一个不确定大小的数组时不起作用。只需使用正确的 C++ 方法:
template <typename T, std::size_t N>
constexpr std::size_t size(T(&)[N]) {
return N;
}
在数组上使用 size()
可以正常工作。在它不适用的情况下使用它将是一个编译时错误,例如,在指针上。
静态数组的 sizeof 技术工作更正,不会有任何问题。如上文所述,对于动态数组和指针数据,它将无法正常工作。
摘自 TopCoder article:
The expression
sizeof(data)/sizeof(data[0])
returns the size of the arraydata
, but only in a few cases, so don’t use it anywhere except in such constructions.(C programmers will agree with me!)
为了获得数组大小,我一直在对所有基本类型.
使用这个表达式sizeof(data)/sizeof(data[0])
有人知道上面的表达式 不应该 的任何情况吗?
如果 data
是这样声明的:
int *data;
然后 space 分配如下:
data = malloc( NUM_ELEMENTS * sizeof(int) );
那你的技术就不行了,因为sizeof(data)
是指针的大小,不是数组的内容。
sizeof
方法可以编译,但在给它一个指针或一个不确定大小的数组时不起作用。只需使用正确的 C++ 方法:
template <typename T, std::size_t N>
constexpr std::size_t size(T(&)[N]) {
return N;
}
在数组上使用 size()
可以正常工作。在它不适用的情况下使用它将是一个编译时错误,例如,在指针上。
静态数组的 sizeof 技术工作更正,不会有任何问题。如上文所述,对于动态数组和指针数据,它将无法正常工作。