How can I check to see if an element in an array is empty in C?
if(array[i] == NULL)
Doesn't seem to work.
To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to null .
✓to check whether an array is empty or not just iterate the elements of the array and compare them with null character '/0'. ✓you can also declare an empty array like this arr[]={}. Then use the sizeof function, if it returns 0 your array is empty.
char name[32]; The name array is null string. That doesn't mean that it has a null character ( '\0' ) at element zero. It means that name hasn't been assigned a value. Had it been assigned a value, and the contents removed or replaced by a null character at element zero, then it becomes an empty string.
An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.
What do you mean with empty?
When a C program is executed, variables that you don't explicitly initialize have got unpredictable values.
You need to set all of your array cells to NULL (or to 0, or to whatever value represents emptyness in your program logic) and then you can check it in the way you did:
int *array[3] = { NULL, NULL, NULL }; // array of three "empty" pointers
...
for( i = 0; i < 3; ++ i ) {
if( array[i] == NULL ) {
// i-th cell is "empty"
}
}
Question answer:
What you posted is the correct code.
Elaboration:
If it "doesn't seem to work", perhaps the problem does not lie at this location in your code. If you would post a more complete example of what you have, the code's expected behavior and actual behavior, we may be able to help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With