以下是我的想法:sizeof()
是一个计算变量有多大的运算符。 sizeof(variable type)
可以计算某种类型的大小。数组中元素的数量由sizeof(<array name>) / sizeof(variable type)
给出。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
double b[] = {1 , 2 , 3 , 4 , 5};
printf("How many elements the array contains : %d\n" , sizeof(b) / sizeof(double));
system("pause");
return 0;
}
输出为5,这是正确的。
我想知道是否有更有效的方法来计算它?比方说,C函数。
答案 0 :(得分:5)
您的代码是计算数组中元素数量的正确和推荐方法。只是为了健壮,您可以像
一样编写它 ( sizeof(b) / sizeof(b[0]) ); // independent of the data type of array
但是,FWIW,请注意,如果指针类型变量代表 数组,这将不起作用。
答案 1 :(得分:1)
目前,您的代码效率最高,但正如其他人所建议的那样,最好使用
( sizeof( b ) / sizeof( b[0] ) );
因为在这种情况下你不必担心数据类型。
但要注意,您实际上是在获取可以存储在数组中的元素数量,而不是已存储的元素数量。所以,如果你试试
double b[10];
printf("How many elements the array contains : %d\n" , sizeof(b) / sizeof(b[0]));
结果将是10,即使其中没有存储任何元素。 Example