【问题标题】:assignment from incompatible pointer type [enabled by default]来自不兼容指针类型的赋值[默认启用]
【发布时间】:2015-10-29 05:10:54
【问题描述】:

为什么我在insertNode() 中收到此警告:

warning: assignment from incompatible pointer type [enabled by default]|

在这一行:

 head->next = newNode; //point head's next to the newNode

warning: initialization from incompatible pointer type [enabled by default]|

在这一行:

 Node *current = head->next; 

在我的main() 函数中,我也有这个警告:

warning: passing argument 1 of 'insertNode' from incompatible pointer type [enabled by default]|

在这一行:

insertNode(&head, num);

我的代码中有许多与这些警告类似的其他警告。我该如何修复它们?

 typedef struct NodeStruct{
      int data;
      struct Node *next;
 }Node;

void insertNode(Node *head, int data){
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;

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

    else{
        Node *current = head->next; 
        while(current != NULL && current->data < data){
            current = current->next;
        }
        newNode->next = current->next;
        current->next = newNode; 
    }
}

int main(int argc, char *argv[])
{
    Node *head = malloc(sizeof(NodeStruct));
    head->next = null;
    insert(head, 22);
    insert(head, 55);
    insert(head, 44);
    insert(head, 2);
    insert(head, 2112);
    insert(head, 3);


    printList(head);
    return 0;

}

【问题讨论】:

  • 你能显示结构定义吗?还有insertNode(&amp;head, num); -> insertNode(head, num);
  • @haris,为什么head 应该没有&amp;
  • 因为head 是指向Node 的指针,这就是您在insertNode(Node *head, int data) 中收到的内容
  • @Haris,我该如何修复不兼容的类型?
  • 我认为其他警告是因为我在上面指出的一个错误。请更正并检查一次。

标签: c pointers


【解决方案1】:

main-

insertNode(&head, num);
           ^ don't pass address

它需要Node *,你应该这样称呼它-

insertNode(head, num);

其他警告是由于上述错误,因为您将head 的地址而不是head 传递给函数。

也可以在struct NodeStruct 更改这个 -

struct Node *next;         // you cannot reference Node in struct itself

到-

struct NodeStruct *next;   //You need to use structure name 

【讨论】:

  • 然后把-&gt;改成.,@ameyCU ??
  • @John,不,你不需要改变它。
  • @John 为什么会这样? head 仍然是一个结构体指针。
  • 因为现在它给了我错误:error: invalid type argument of '-&gt;' (have 'Node')| 在具有 -&gt; 运算符的行中。 @ameyCU
  • @John 发现。请看答案。
猜你喜欢
  • 1970-01-01
  • 2014-11-03
  • 1970-01-01
  • 2019-08-09
  • 2014-12-14
  • 2019-06-05
  • 2015-03-09
  • 2014-07-27
  • 1970-01-01
相关资源
最近更新 更多