c语言 - Pop 无法正常工作 - 起始项不会取消排队



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

#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("%dn", 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("%dn",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()给您的原始指针的指针,这可能会导致内存泄漏,因为您会丢失对内存的跟踪。

相关内容

最新更新