Home > Article > Backend Development > How to get the length of an array in C language
In C language, after defining an array, you can use the sizeof command to obtain the length of the array [the number of elements that can be accommodated]. It is not feasible to obtain the length of the array by passing the array name parameter to the subfunction.
In C language, after defining an array, you can use the sizeof command to obtain the length of the array (the number of elements that can be accommodated)
For example:
{ int data[4]; int length; length=sizeof(data)/sizeof(data[0]); //数组占内存总空间,除以单个元素占内存空间大小 printf("length of data[4]=%d", length ); //输出length of data[4]=4 }
It is not feasible to obtain the array length by passing the array name parameter to the sub-function. For example:
int getLength(int[] a){ int length; length=sizeof(a)/sizeof(a[0]); //这样是错误的,得到的结果永远是1 return length; } 因为,a是函数参数,到了本函数中,a只是一个指针(地址,系统在本函数运行时,是不知道a所表示的地址有多大的数据存储空间, 这里只是告诉函数:一个数据存储空间首地址),所以,sizoef(a)的结果是指针变量a占内存的大小,一般在32位机上是4个字节。 a[0]是int类型,sizeof(a[0])也是4个字节,所以,结果永远是1。
Therefore, to obtain the array length, the effect can only be achieved by using the above method in the code area where the array is defined.
Recommended tutorial: "c Language Tutorial"
The above is the detailed content of How to get the length of an array in C language. For more information, please follow other related articles on the PHP Chinese website!