-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?

4
  • 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 Commented Aug 31, 2021 at 6: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. Commented Aug 31, 2021 at 6:51
  • 1
    The Definitive C++ Book Guide and List Commented Aug 31, 2021 at 6: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; Commented Aug 31, 2021 at 7:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This will return 10 and is not what the OP is asking
That's true, misread. Saw total number of elements in the array and went with it. C++ doesn't work like that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.