Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

c - 如何确定C语言中数组的大小?(How do I determine the size of my array in C?)

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

(如何确定C语言中数组的大小?)

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

(也就是说,数组可以容纳多少个元素?)

  ask by Mark Harrison translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...