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#
It's all filled, so the answer is whatever the size of your array is. An array is a contiguous memory segment, so it is filled by default with whatever was at that memory location before.
But you probably want to know how much of it is filled with data that you care about, and not with random data. In that case, there is no way of knowing that unless you keep track of it yourself.
Subtract the number of empty elements from the size of the array. ;-)
Sorry, there is no way (except you keeping track), to tell whether an array element has been modified.
You need to keep track of this yourself. There is no concept of "full" (or anything in between for that matter): you have to define this.
Of course if the elements are contiguous in the array, you could use a
NULL
element to signify the "end" of the array thus defining a "full" state at the same time.In a C array, any element is an object. It's not like in Java where you have references that first have to be assigned to point to objects. Anything in C behaves like a primitive type in Java.
If you have an array of pointers in C, you may view this similar to how things in Java work. You can use null pointers to designate "is not filled to point to an object":
Then you can simply test with
You could do a
while(yourArray != NULL)
loop and through the loop just increment an integer value and that should tell you.From the C language perspective, there is no concept of "filled". Once an array is defined, memory is allocated to it. For arrays like array1 (see example below), elements get initialized to 0. However, for arrays like array2, the elements can have random value.
So, the notion of "filled" has to be supplied by the program. One possible to "in-band" way is to: (a) Choose one specific value of the element type (e.g. 0xFFFFFFFF) and use it to detect fill/empty property of each array element (However, realize that this approach takes away one otherwise valid value from the element set.), and (b) "initialize" all the elements of the array to that disallowed value at suitable position in the program scope. (c) To find array fill level, count the number of valid elements.