Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to see if an element is null in an array in C?

Tags:

c

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.

like image 322
Alex Avatar asked Nov 14 '10 17:11

Alex


People also ask

How do you check if an element of an array is null?

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 .

How do you check if a spot in an array is empty C?

✓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.

What is null in array in C?

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.

Can null be an element in an array?

An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.


2 Answers

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"
  }
}
like image 178
peoro Avatar answered Oct 15 '22 03:10

peoro


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.

like image 34
Billy ONeal Avatar answered Oct 15 '22 02:10

Billy ONeal