Executive summary:
(执行摘要:)
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
Full answer:
(完整答案:)
To determine the size of your array in bytes, you can use the sizeof
operator:
(要确定以字节为单位的数组大小,可以使用sizeof
运算符:)
int a[17];
size_t n = sizeof(a);
On my computer, ints are 4 bytes long, so n is 68.
(在我的计算机上,整数是4个字节长,所以n是68。)
To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
(为了确定数组中元素的数量,我们可以将数组的总大小除以数组元素的大小。)
You could do this with the type, like this: (您可以使用以下类型来执行此操作:)
int a[17];
size_t n = sizeof(a) / sizeof(int);
and get the proper answer (68 / 4 = 17), but if the type of a
changed you would have a nasty bug if you forgot to change the sizeof(int)
as well.
(并得到正确的答案(68/4 = 17),但如果类型a
改你将有一个讨厌的错误,如果你忘了改变sizeof(int)
为好。)
So the preferred divisor is sizeof(a[0])
, the size of the zeroeth element of the array.
(因此,首选除数是sizeof(a[0])
,即数组的第零个元素的大小。)
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
Another advantage is that you can now easily parameterize the array name in a macro and get:
(另一个优点是,您现在可以轻松地在宏中参数化数组名称并获得:)
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…