Pop 无法正常工作 - 起始项目不会出队

Pop does not work like it should - the start item isn't going to be dequeued

我的 C 代码有点问题。我想用一些功能实现一个简单的队列,但是弹出功能不起作用。起始项目不会出队。我只是不知道为什么。如果你能帮助我,你真是太好了。 这是代码:

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

struct item{
  struct item* toNext;
  int value;
};
void printQueue(struct item* start){
  if(start == NULL){
      printf("\n");
    return;
  }
  else{
    printf("%d\n", start->value);
    printQueue(start->toNext);
  }
}
int pop(struct item* start){
  if(start == NULL){
    return -1;
  }
  else{
    int tmp = start->value;
    start = NULL;
    return tmp;
  }
}
int main(int argc, char *argv[]){
  struct item* beginning;
  struct item* current;
  struct item* next;
  current = (struct item*) malloc(sizeof(struct item)); 
  current->value = 1;
  current->toNext = NULL;
  beginning = current;
  int i;
  for(i = 2; i <= 4; i++){
    next = (struct item*) malloc(sizeof(struct item)); 
    next-> value = i;
    next-> toNext = NULL;
    current->toNext = next;
    current = next; // TODO

  }
  printQueue(beginning);
  int tmp = pop(beginning);
  printf("%d\n",tmp);
  printQueue(beginning);

  return 0;
}

输出为:

1
2
3
4

1
1
2
3
4

虽然应该是:

1
2
3
4

1

2
3
4

有人知道这里出了什么问题吗?

如果你想在你的pop函数中修改你的起始指针,你需要传递的不仅仅是一个指针,而是一个指向指针的指针,这样你不仅可以修改指向的数据,但指针本身。因此,您的函数签名需要变为:

int pop(struct item** start)

这将需要稍微修改您的代码,因为您需要解引用一次才能到达起始指针,解引用两次才能到达实际数据。此外,将起始指针设置为 null 将清除整个列表。您必须将开始指针设置为列表中的下一项。你的函数最终看起来像这样:

int pop(struct item** start){
  // Dereference once to get to beginning pointer
  if(*start == NULL){
    return -1;
  }
  else{
    // Dereference, then use arrow to get pointer to data, then data itself
    int tmp = (*start)->value;
    // Move beginning pointer to next item
    *start = (*start)->next;
    return tmp;
  }
}

请注意,如果您不存储 malloc() 给您的原始指针的指针,这可能会导致内存泄漏,因为您会丢失内存。