如何确定 C 中数组的大小? [英] How do I determine the size of my array in C?

查看:74
本文介绍了如何确定 C 中数组的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中确定数组的大小?

How do I determine the size of my array in C?

也就是数组能容纳多少元素?

That is, the number of elements the array can hold?

推荐答案

执行摘要:

int a[17];
size_t n = sizeof(a)/sizeof(a[0]);

<小时>

完整答案:

要以字节为单位确定数组的大小,可以使用 sizeof操作员:

To determine the size of your array in bytes, you can use the sizeof operator:

int a[17];
size_t n = sizeof(a);

在我的电脑上,整数是 4 个字节长,所以 n 是 68.

On my computer, ints are 4 bytes long, so n is 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);

并得到正确答案 (68/4 = 17),但如果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.

所以首选的除数是 sizeof(a[0]) 或等效的 sizeof(*a),即数组第一个元素的大小.>

So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array.

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);

这篇关于如何确定 C 中数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆