If you have an array in C, how can you find out how much of it is filled?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- How to get the maximum of more than 2 numbers in V
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
in C, there is no built-in way of knowing how many elements are filled with data that you care about. You will need to build it yourself. As was previously said, if you can have a value that will not represent anything(0 for example), you could :
On the other hand, if you need the extent of your data to be represented, You will need a flag array that will keep track of the elements that are set and those that aren't :
For example, if you have an array of 32 elements or less, you only need an unsigned integer to keep track of your array: 1100010 ...
Values:
1 -> Set
2 -> Set
3 -> no set
4 -> not set
5 -> not set
6 -> set
etc.
So Whenever you are filling an element you call the function that sets the correct bit and when you are "unfilling" the data you unset the bit that corresponds to it.
Once this is done, All you would need to do is simply call a popcount over the flag array.
I agree with other answers, but I can suggest you a way to make your work easier. You can manage the array like an object and control the adding and the removing of data. If you implement two functions, one to add elements and one to remove them, with the proper logic to manage fragmentation and multi-threading, you can track the number of elements into the array reading a counter, which is written only by add and remove function. So you don't have to execute a loop every time you need to count the elements.