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

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.


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"
  }
}

Tags:

C