Reputation: 93
Here's my thinking: sizeof()
is an operator that calculates how big a variable is. sizeof(variable type)
can calculate how big a certain type is. The number of the elements in an array is given by sizeof(<array name>) / sizeof(variable type)
.
Here's my code:
#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;
}
The output is 5 which is correct.
I wonder if there is some more efficient way to calculate that? Say, a C function.
Upvotes: 3
Views: 180
Reputation: 7006
Currently, your code is the most efficient, although as suggested by others, it's better to use
( sizeof( b ) / sizeof( b[0] ) );
as you won't have to worry about the data type in this case.
But beware, you are actually getting the number of elements that can be stored in the array, not the number of elements already stored. So, if you try
double b[10];
printf("How many elements the array contains : %d\n" , sizeof(b) / sizeof(b[0]));
The outcome would be 10, even though no elements have been stored in it. Example
Upvotes: 1
Reputation: 134286
Your code is the correct and recommended way of counting the number of elements in the array. Just for sake of robustness, you can write it like
( sizeof(b) / sizeof(b[0]) ); // independent of the data type of array
However, FWIW, please be aware, this will not work in case of pointer type variables representing the array.
Upvotes: 5