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

查看:203
本文介绍了如何确定我使用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];
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];
int n = sizeof(a);

在我的电脑上,int为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];
int 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.

所以preferred除数为的sizeof(A [0])的大小
数组的第0个元素。

So the preferred divisor is sizeof(a[0]), the size of the zeroeth element of the array.

int a[17];
int 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];
int n = NELEMS(a);

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

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