3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
PPJack
  • 95
  • 1
  • 6
  • This is the only efficient way in c. – haccks May 05 '15 at 04:57
  • 8
    More efficient? It's done at compile time. What more efficiency do you want? Fewer keystrokes? – Cornstalks May 05 '15 at 04:57
  • 7
    I think `sizeof(b)/sizeof(b[0])` is more suitable – Santosh A May 05 '15 at 04:57
  • 2
    Also, strictly speaking, you cannot `printf` a `size_t` with `%d` (see http://stackoverflow.com/q/2524611/). – Nemo May 05 '15 at 05:11
  • 1
    Microsoft has the [`_countof` macro](https://msdn.microsoft.com/en-us/library/ms175773.aspx), but that's just doing the same thing as `sizeof(a) / sizeof(a[0])`. In C++, there's an additional requirement that the argument to `_countof` is actually an array, else a compilation error will result. You might create your own macro actually: `#define arr_len(a) (sizeof(a) / sizeof(a[0]))`. Obviously you can test for `_countof` and use that if you like. It would aid C++ compiler compatibility if that's desired at all. –  May 05 '15 at 05:32

2 Answers2

5

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

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

Arun A S
  • 6,421
  • 4
  • 29
  • 43