我的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("%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
有谁知道这里有什么问题吗? 谢谢你的回答。
答案 0 :(得分: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()
提供的原始指针存储指针,这可能会导致内存泄漏,因为您将丢失内存跟踪。