运算符sizeof
sizeof() operator returns the total number of size occupied by a variable, since array is also a variable, we can get the occupied size of array elements.
sizeof()运算符返回变量占用的大小总数,由于array也是变量,我们可以获取数组元素占用的大小。
逻辑 (Logic)
Get the occupied size of all array elements and divide it with the size of array type. Let suppose there is an integer array with 5 elements then size of the array will be 5*4=20 and the size of array type will be 4. Divide 20 by the 4 answer will be 5 which is the number of array elements.
获取所有数组元素的占用大小,然后将其除以数组类型的大小。 假设有一个包含5个元素的整数数组,那么数组的大小将为5 * 4 = 20,数组类型的大小将为4。20除以4的答案将为5,这是数组元素的数量。
Let's consider the following program
让我们考虑以下程序
程序计算C语言中数组元素的总数 (Program to count total number of array elements in C)
#include <stdio.h>
int main()
{
int arr[]={10,20,30,40,50};
int n;
n=sizeof(arr)/sizeof(int);
printf("Number of elemenets are: %d\n",n);
return 0;
}
Output
输出量
Number of elemenets are: 5
另一种方法 (Another method)
We can divide the occupied size of all array elements by size of any one array element. Consider the following statement:
我们可以将所有数组元素的占用大小除以任何一个数组元素的大小。 考虑以下语句:
n=sizeof(arr)/sizeof(arr[0]);
翻译自: https://www.includehelp.com/code-snippets/c-program-to-count-array-elements-by-using-sizeof-operator.aspx
运算符sizeof