I have an array like this:
int a[100];
I am filling only the first 4 elements in this array:
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
When I do sizeof(a)/sizeof(a[0]) it returns 100.
Is there a way I can get number of elements to which I have assinged a value and thus filtering out the remaining 96 unassigned elements?
thanks
All elements must be assigned to something, thus the array always has 100 elements. If you can ensure all the elements are initialized to a special value which means “unassigned” to you (e.g. -1), you can work it out like this:
If you just want to know how many elements are in an array, you have these options:
Don’t use an array, use
std::vector, which has asize()function, and is generally a better choice than a basic arrayKeep track of the element count yourself, in a separate variable
Use the special “unassigned” value as described above, and use
std::findto find the first one, and work out how many are there by subtracting the address of the zeroth element from that. This is a pretty ugly solution.For a beginner,
std::vectoris a much better choice. You can use it like this: