-1

I need help in calculating the total number of elements stored in an array. For example if I have something like,

int a[10] = {1 , 2 , 3 , 4 , 5 , 6 , 7 , 8};

As you can see that the elements of the array are less than the size of the array i.e. 10. Then how do I calculate the total number of elements in the array?

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 4
    An array defined as `a[10]` has 10 elements, the fact that you're not assigning all of them doesn't change this fact. Your compiler most likely initializes the rest to 0 – po.pe Aug 31 '21 at 06:49
  • 1
    "As you can see that the elements of the array are less than the size of the array" No, I cannot in fact see that, because it is not the case. C++ does not work like that. – Karl Knechtel Aug 31 '21 at 06:51
  • 1
    [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Evg Aug 31 '21 at 06:55
  • Contrary to what you might think, your array has 10 elements, not 8, and most likely your other 2 elements have a value of 0. If you don't resize the array, you can find the number of elements in the array like this. `std::cout << "Array Length= " << (sizeof(a)/sizeof(*a))<<"\n";` or `int arrayLength=0; for (auto i : a) {++arrayLength;} std::cout<< "Array Length= " << arrayLength;` – east1000 Aug 31 '21 at 07:04

1 Answers1

0

This returns the size of the array which is 10:

(int)( sizeof(a) / sizeof(a[0]));

C++ compiler cant tell the difference between actual values and garbage ones.

DragonInTraining
  • 385
  • 1
  • 12