C 中有没有标准函数可以返回数组的长度? [英] Is there a standard function in C that would return the length of an array?
问题描述
C 中有没有标准函数可以返回数组的长度?
Is there a standard function in C that would return the length of an array?
推荐答案
通常其他答案中描述的技术被封装在一个宏中,以使其更容易理解.类似的东西:
Often the technique described in other answers is encapsulated in a macro to make it easier on the eyes. Something like:
#define COUNT_OF( arr) (sizeof(arr)/sizeof(0[arr]))
请注意,上面的宏使用了一个小技巧,将数组名称放入索引运算符 ('[]
') 而不是 0
- 这是在如果宏在 C++ 代码中被错误地用于重载 operator[]()
的项目.编译器会抱怨而不是给出一个糟糕的结果.
Note that the macro above uses a small trick of putting the array name in the index operator ('[]
') instead of the 0
- this is done in case the macro is mistakenly used in C++ code with an item that overloads operator[]()
. The compiler will complain instead of giving a bad result.
但是,还要注意,如果您碰巧传递的是指针而不是数组,宏会默默地给出一个糟糕的结果——这是使用这种技术的主要问题之一.
However, also note that if you happen to pass a pointer instead of an array, the macro will silently give a bad result - this is one of the major problems with using this technique.
我最近开始使用从 Google Chromium 代码库中窃取的更复杂的版本:
I have recently started to use a more complex version that I stole from Google Chromium's codebase:
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
在这个版本中,如果一个指针被错误地作为参数传递,编译器会在某些情况下抱怨——特别是如果指针的大小不能被指针指向的对象的大小整除.在这种情况下,除以零将导致编译器出错.实际上,我使用过的至少一个编译器会给出警告而不是错误 - 我不确定它会为除以零的表达式生成什么.
In this version if a pointer is mistakenly passed as the argument, the compiler will complain in some cases - specifically if the pointer's size isn't evenly divisible by the size of the object the pointer points to. In that situation a divide-by-zero will cause the compiler to error out. Actually at least one compiler I've used gives a warning instead of an error - I'm not sure what it generates for the expression that has a divide by zero in it.
该宏不会关闭错误使用它的门,但它与我在直 C 中见过的一样接近.
That macro doesn't close the door on using it erroneously, but it comes as close as I've ever seen in straight C.
如果您在使用 C++ 时想要更安全的解决方案,请查看 不使用宏的编译时间 sizeof_array 描述了微软在 winnt.h
中使用的一种相当复杂的基于模板的方法.
If you want an even safer solution for when you're working in C++, take a look at Compile time sizeof_array without using a macro which describes a rather complex template-based method Microsoft uses in winnt.h
.
这篇关于C 中有没有标准函数可以返回数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!