求数组长度

转载自:http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c

------------------------------------------------- 我是分割线 --------------------------------------------------------

Executive summary:

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

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

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

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

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.

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);
请使用浏览器的分享功能分享到微信等