0

I'm trying to get the number of floats in the following array:

float coins[] = {0.25, 0.10, 0.05};
printf("%i", sizeof(coins));

I get 12.

I am trying to get 3.

What am I missing here?

Nat Ritmeyer
  • 5,634
  • 8
  • 45
  • 58
John
  • 3,866
  • 6
  • 33
  • 37

3 Answers3

2

you can get the number of elements in array by,

array_size/single_array_element_size

i.e.

sizeof(coins)/sizeof(float)
LearningC
  • 3,182
  • 1
  • 12
  • 19
1

Use the expression sizeof coins / sizeof *coins to get the number of elements of the array.

sizeof yields the size in bytes of its operand. So if you pass an array operand you will get the storage size in bytes of the array not the number of elements.

ouah
  • 142,963
  • 15
  • 272
  • 331
0
int main(void) 
{
   float coins[] = {0.25, 0.10, 0.05};

   int n = sizeof(coins)/sizeof(coins[0]);
   printf("%d", n);
   return 0;
}
Engineer2021
  • 3,288
  • 6
  • 29
  • 51