There is no generic way to do that as all elements of an array always contain a value.
Couple common ways to handle that:
- keep track of "valid" elements yourself as you suggested in the post.
- have sentinel element that marks "missing" value and check each element for it - first element with such value will mark "end of filled array". For reference types you can use
null
, for other types sometimes there is specific value that rarely used and can be treated as "missing" - i.e. max value of integer types.
The second approach is the way C-style strings are implemented - it is array of characters up to 0
character - so you can always compute length of the string even if it is stored in longer array of chars.