87 字
1 分钟
Calculating the Number of Elements in a C++ Array
int i_max(int a[]) {
int tmp=a[0];
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
if (tmp < a[i])
tmp = a[i];
// tmp < a[i] ? tmp = a[i] : tmp = tmp;
return tmp;
}

The key code

sizeof(a) / sizeof(a[0])

This snippet is the widely-used(?) code for calculating the number of elements in an array

But when the array is a pointer, errors often occur (C6384)

Solution:

Pass using a struct

struct a{
int b[5]}
xxx(struct a)
{
sizeof(a.b);
}

It seems that when passing, the array becomes a pointer…

Calculating the Number of Elements in a C++ Array
https://tski.uk/blog/en/cpp-array-element-count/
作者
Tokisaki Galaxy
发布于
2019-12-03
许可协议
CC BY