Checknullarray与结构

时间:2013-02-28 18:42:41

标签: c arrays for-loop structure

struct contact list[3];
int checknullarray()
{
    for(int x=0;x<10;x++)
    {
        if(strlen(contact[x].name)==0)
        {
        return x;
        break;
        }
    }
}

我遇到了checknullarray的问题。它说我的类型名称(contact[x].name)是不允许的。我现在该怎么办?

2 个答案:

答案 0 :(得分:1)

假设联系人有像char name[n];

这样的成员
struct contact list[3];

int checknullarray(void) /* void is a better option when no params */
{
    for (int x = 0; x < 10; x++) /* 3 or 10 ? I think you want x < 3 */
    {
        /*
        if(strlen(contact[x].name)==0) No need to strlen, you can check if name[0] == 0
        */
        if (list[x].name[0] == '\0')
        {
               return x;
            /*
               break; why break if you return in previous line?
            */
        }
    }
    return x; /* As suggested by qPCR4vir you need an alternative return */
}

答案 1 :(得分:1)

只是为了好玩:-)(另一种解决方案很好)

#include "contact.h"
#define N 3
struct contact list[N];

int checknullarray(void)
{
    int x;
    for ( x = 0; x < N && *list[x].name; x++) ;
    return x; 
}
int main(void)
{
   /* initialice list */
   int R;
   R=checknullarray();
   if (R==N) /* No name in list =="" */;
}