有没有在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 code错误地使用了与重载一个项目运算符[]()
。编译器会抱怨,而不是让一个坏的结果。
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.
我最近开始使用更复杂的版本,我从谷歌Chromium的codeBase的偷了:
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])))))
在这个版本中,如果一个指针作为参数错误地传递,编译器会抱怨在某些情况下 - 尤其如果指针的大小不是由对象的大小的指针指向整除。在这种情况下除以零会导致编译器错误的。其实至少有一个编译器,我使用发出警告,而不是一个错误 - 我不知道它会产生对具有在其零鸿沟前pression。
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 ++中工作的一个更安全的解决方案,看看<一个href=\"http://stackoverflow.com/questions/1500363/compile-time-sizeofarray-without-using-a-macro/1500917#1500917\">http://stackoverflow.com/questions/1500363/compile-time-sizeofarray-without-using-a-macro/1500917#1500917它描述了 WINNT.H
一个相当复杂的基于模板的方法,微软使用。
If you want an even safer solution for when you're working in C++, take a look at http://stackoverflow.com/questions/1500363/compile-time-sizeofarray-without-using-a-macro/1500917#1500917 which describes a rather complex template-based method Microsoft uses in winnt.h
.
这篇关于有没有在C标准函数将返回数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!