anonym
anonym

Reputation: 145

How do I check how many elements are empty in an array?

I am trying to save how many empty elements there are in an array. This is what I have done so far but it prints out that all lines are "not empty" which is wrong. How can I do this?

char arr[10][50]={NULL};
int lines;

//inserting values to arr

for(int i=0;i<10;i++){
   if(arr[i] == NULL){
       lines++;
       printf("empty");
   }
   else
       printf("not empty");
}

Upvotes: 2

Views: 352

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

Two problems:

  1. This:

    char arr[10][50]={NULL};
    

    should be

    char arr[10][50]={{0}}; /* Initializes the whole 2D array with zeros */
    

    or

    char arr[10][50]={{'\0'}}; /* Does the same thing as above; '\0' == 0 */
    

    The issues here were:

    1. NULL is usually used with pointers, but arr is designed to store chars, and chars aren't pointers.
    2. You should use an extra pair of braces as you are initializing a 2D array, not a 1D array.
  1. Here:

    if(arr[i] == NULL)
    

    You check if each row of your 2D array is NULL. In other words, you are checking if each subarray has an address NULL. This will not be true and is probably contratry to what you thought.

    @Joachim Pileborg's answer gives more insight on this issue and a possible solution for it.

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409166

When you do arr[i] == NULL then arr[i] decays to a pointer to the first element of the array in arr[i] (i.e. &arr[i][0]), and that pointer will never be NULL.

I suspect you want e.g. something like arr[i][0] == '\0'.

Upvotes: 8

Related Questions