Calculating the Number of Elements in a C++ Array

1
2
3
4
5
6
7
8
9
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;
}

关键代码

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

这一段是网上流行(?)计算数组元素个数的代码

但是在数组为指针的时候,经常会出错(C6384)

解决方法:

使用结构(struct)传递

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

似乎是因为在传递的时候,数组变成了一个指针…

1
2
3
4
5
6
7
8
9
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;
}

Key code

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

This piece is the widely circulated (?) code for calculating the number of elements in an array.

However, it often fails (C6384) when the array is a pointer.

Solution:

Use a structure (struct) for passing.

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

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


Calculating the Number of Elements in a C++ Array
https://tokisaki.top/blog/cpp-array-element-count/
作者
Tokisaki Galaxy
发布于
2019年12月3日
许可协议