C code Count elements in array that are not null

5.2k Views Asked by At

going over old exam papers and doing questions, for this one:

array is:

char* s[]={"one","two",NULL,NULL,"five","",""};

using function name:

int inUse(char *s[],int len)

I have to determine the number of elements that are not NULL.

I have come up with:

int count=0;

for(i=0; i<7, i++)
{
    if(s !=NULL)
    {
        count ++;
    }
}

Is this correct? thankyou

REVISED:

int inUse(char *s[],int len)
{

    int count=0;

    for(i=0; i<len, i++)
    {
        if(s[i] != NULL)
        {
            count ++;
        }
    }

    return count;
}
1

There are 1 best solutions below

3
On BEST ANSWER

First of all,

char s*[]={"one","two",NULL,NULL,five,"",""};

doesn't compile. Did you mean

char* s[]={"one","two",NULL,NULL,"five","",""};

Secondly, I assume you call your function using

inUse(s, 7);

/* OR */

inUse(s, sizeof(s) / sizeof(*s));

Thirdly, you should change

if(s !=NULL)

to

if(s[i] != NULL)

since you want to check if individual elements of the array are not NULL.

Lastly, I assume that you return count from the function.