如果我不想将元素数量作为另一个参数传递,如何计算数组中的元素数量,
fun(a, sizeof(a)/sizeof(*a));
并接收为
int fun(int a[], int limit)
{
}
最佳答案
How can I calculate the number of elements in the array
你不能。
if I don't want to pass the number of elements as another argument
你必须。
这里是C区,那里没有保姆,也没有魔杖。如果您需要跟踪一条信息(例如数组的长度),您必须自己这样做。这种明确性是我们使用 C 的原因,因此我们确切知道正在发生什么,而编译器不会在我们背后做疯狂的事情。
<小时/>你会看到这样的宏:
#define ARRAY_LENGTH(x) (sizeof(x) / sizeof(x[0]))
但是要小心!这只适用于数组,其大小在编译时就已知。它不适用于任意指针。
Linux 内核以安全的方式提供了这个宏:
kernel.h :
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
/* &a[0] degrades to a pointer: a different type from an array */
#define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
关于计算传递给函数的数组中的元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126971/