指针&方法中的函数调用

时间:2012-09-10 12:01:57

标签: c pointers

我得到了几个编译错误,我无法弄清楚它们。它可能是简单的东西,但我不能弄明白。我猜测指针必须改变,但我不知道到底是什么。我试图改变指针,但它仍会给出错误。我会感激任何帮助。这些错误是:

  passing argument 1 of 'compare' from incompatible pointer type
  expected 'struct person *' but argument is of type 'char *'
  passing argument 2 of 'compare' from incompatible pointer type
  expected 'struct person *' but argument is of type 'char *'


  struct person *insert(struct person *head, char *personName, int personAge, int        (*compare)(struct person *a, struct person *b)) 
  {  
    struct person *new;

    new = (struct person*)malloc(sizeof(struct person));
    if(new == NULL)
    fprintf(stderr,"Couldn't allocate memory!");

    new->name = personName;
    new->age = personAge;  

    if(head == NULL)
    { 
      new->next = head;
      head = new; 
    }

    else
    {
      while(head != NULL)
      head = head->next;

      //compile errors
      if(compare(new->name,head->name) < 0)
      { 
        new->next=head;
     head->next=NULL;
      }

      else
      {
        head->next = new;
        new->next = NULL;
      }
    }//else  
      return head;

  }//method



  //----------------------------compare--------------------------------//
   int compare(struct person *a, struct person *b)
   {
      int result = strcmp(a->name, b->name);
      return result;
   }

3 个答案:

答案 0 :(得分:2)

尝试将compare(new->name,head->name)替换为compare(new, head)

答案 1 :(得分:2)

您不应该使用compare(new,head)代替compare(new->name,head->name)吗?

答案 2 :(得分:1)

您的compare函数需要2 person个指针,但您已经传递了2 char个指针(名称)。