嘿!我正在尝试使用 C 中的链表尝试所有可能性,但是当我尝试删除第一项 (pop) 时,我不断收到错误消息

Hey! I'm trying to try out all of the possibilities with linked lists in C, but when I try to remove the first item (pop), I keep getting an error

这是我的代码,问题出在函数 pop

在这个程序中,我只是创建一个链表,有两个值,1 和 2。然后我简单地打印列表,然后我再次打印,但是在 运行 弹出函数之后。但是,我将 运行 保留为 warning/error。如果您能提供帮助,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int val;
    struct node* next;
}
node;

//Print list
void print_list(node * header) {
    node * current = header;

    while (current != NULL) {
        printf("%d\n", current->val);
        current = current->next;
    }
}

//Removing from the list (pop)
int pop(node** header)
{
  if (*header == NULL)
  {
    return -1;
  }

  node* next_node = *header;
  int retvalue = next_node->val;

  (*header) = (*header)->next;

  free(next_node);

  return retvalue;
}


int main(void)
{
  //Alllocating the header of the list
  node *header = (node*) malloc(sizeof(node));

  //Making sure header doesn't return NULL
  if (header == NULL)
  {
    return 1;
  }

  header->val = 1;
  header->next = (node*) malloc(sizeof(node));
  header->next->val = 2;
  header->next->next = NULL;

  printf("Here is the first list:\n");
  print_list(header);
  printf("Here is the list with a removed value (start)(pop):\n");
  pop(header);
  print_list(header);


}

这是我从编译器得到的错误:

warning: incompatible pointer types passing 'node *' (aka 'struct node *') to parameter of type

      'node **' (aka 'struct node **'); take the address with & [-Wincompatible-pointer-types]
  pop(header);
      ^~~~~~
      &

由于您的 pop() 函数接受一个 指向指针的指针 ,您必须这样传入一个:

pop(&header);

这大概是因为函数可能需要更改该指针并需要直接访问它作为可变参数。

问题是您将 node* 传递给接受 node**pop 函数,您只需要传递 &header 即可使其正常工作。

使用静态分析器可以避免这种微小的错误,它会立即突出显示有问题的代码。

warning: incompatible pointer types passing 'node *' (aka 'struct node *') to parameter of type
'node **' (aka 'struct node **'); take the address with & [-Wincompatible-pointer-types]
  pop(header);
      ^~~~~~
      &

你的编译器错误说明了一切。 函数 int pop(node** header) 接受 address of a pointer of type node 作为它的参数,你只是发送 value of header 这是一个 pointer to the location allocation by malloc.

因此,将 pop(header) 更改为 pop(&header)