codeLover
codeLover

Reputation: 3810

Knowing the number of elements stored in an array in VC++

Is there any way to find the number of elements in an array in VC++ without using for loop.

Let us say array has 16 elements;

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

Now I if I want to get the length to be equal to 7 & NOT 16 (I mean I want to know the number of elements stored in this array instead of getting the number of spaces in the array). Is there any way similiar to the length() functions we have in C#? I am using VC++ on VS2008.

Thanks in advance.

Upvotes: 1

Views: 461

Answers (2)

NPE
NPE

Reputation: 500883

For built-in arrays, the only way to do this is for you to keep track of this "length" yourself. There's no automatic way of doing it.

A better way, however, is to use std::vector<int>. It automatically keeps track of both the current number of elements (the "size") and the number of elements that can be accommodated without re-allocating the array (the "capacity").

Upvotes: 4

Alok Save
Alok Save

Reputation: 206636

No, it is not possible, If you do not fill the entire array the remaining elements will be filled with values depending on type on initialization.

Note that C/C++ do not do bounds checking on arrays neither do they keep track of number if array elements, the language just provides you a contiguous block of memory you asked for, it is your responsibility of how and whether you use it. As well as the number of elements being stored in the array.

You can save yourself a lot of problems and bookkeeping simply by using an std::vector.
It provides you with everything an normal array would but with a number of useful member functions like size() which do the bookkeeping for you about number of elements etc.

Upvotes: 2

Related Questions