c语言中获取数组的长度写法

首先对于一维数组,如:

char a[]={1,2,3,4};
int b[]={1,2,3,4,5};
float c[]={1.0,2.0,3.0};

如何求取这些数组的长度呢?可以使用sizeof(),但由于sizeof()返回的是字节长度,所以可以使用sizeof(x)/sizeof((x)[0])。

#include "stdio.h"
#include "stdlib.h"
#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))

void main(void)
{
char a[] = { 1,2,3,4 };
int b[] = { 1,2,3,4,5 };
float c[] = { 1.0,2.0,3.0 };

int length_a = 0;
int length_b = 0;
int length_c = 0;

length_a = ARRAY_SIZE(a);
length_b = ARRAY_SIZE(b);
length_c = ARRAY_SIZE(c);

printf("length of a[]=%d ", length_a);
printf("length of b[]=%d ", length_b);
printf("length of c[]=%d ", length_c);

system("pause");
}

运行结果如下:

那么对于二维数组呢?
如:

char a[][2] = { 1,2,3,4 };
int b[][3] = { 1,2,3,4,5,6 };
float c[][2] = { 1.0,2.0,3.0,4.0 };

可以使用sizeof(x)/sizeof((x)[0][0])。

#include "stdio.h"
#include "stdlib.h"
#define ARRAY_SIZE_2(x) (sizeof(x)/sizeof((x)[0][0]))

void main(void)
{
char a[][2] = { 1,2,3,4 };
int b[][3] = { 1,2,3,4,5,6 };
float c[][2] = { 1.0,2.0,3.0,4.0 };

int length_a = 0;
int length_b = 0;
int length_c = 0;

length_a = ARRAY_SIZE_2(a);
length_b = ARRAY_SIZE_2(b);
length_c = ARRAY_SIZE_2(c);

printf("length of a[]=%d ", length_a);
printf("length of b[]=%d ", length_b);
printf("length of c[]=%d ", length_c);

system("pause");
}

运行结果如下:


总结:原理就是利用sizeof(),先求取数组元素所占的总的字节长度,再求出一个首元素所占的字节长度(即元素类型的长度),相除即可得到数组的长度。
---------------------
作者:weixin_37536484
来源:CSDN
原文:https://blog.csdn.net/weixin_37536484/article/details/78686028
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/Peequeue/p/10005573.html