Is there a better way to calculate how many elements a one-dimensional array contains?

Here's my thinking: sizeof()

- an operator that calculates how big a variable is. sizeof(variable type)

can calculate how big a certain type is. The number of elements in the array is specified 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));
    return 0;


Result 5, which is correct.

I wonder if there is a more efficient way to calculate this? Let's say function C.


source to share

2 answers

Your code is the correct and recommended way to count the number of elements in an array. Just for the sake of reliability, you can write this as

 ( sizeof(b) / sizeof(b[0]) );   // independent of the data type of array


However, FWIW, remember that this will not work for pointer variables representing an array.



Your code is the most efficient currently, although as suggested by others it is better to use

 ( sizeof( b ) / sizeof( b[0] ) ); 


since you don't have to worry about the data type in this case.

But be careful, 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 result will be 10 even if no items were saved in it. Example



All Articles