2016-01-05 19 views
0

我的C代码有点问题。我想用一些函数实现一个简单的队列,但pop函数不起作用。开始的项目不会被取消。我只是不知道为什么。如果你能帮助我,那你真好。 下面的代码: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 

有谁知道这里有什么问题? 感谢您的回答。

+3

您的pop()函数接收指针的拷贝到队列的头。 (您也可以将其视为接收整个队列的只读“副本”)。但是弹出功能需要修改队列。所以你将不得不重新安排事情。 –

+0

因此,对该副本的任何更改都不会反映在原始副本中(主副本中)。 –

+0

为什么你明确地为'main'中的队列分配节点?所有的队列交互都应该通过队列接口,即函数和一个空队列由一个'NULL'头指针来表示。 (啊,我现在看到的:你有没有'push'功能。) –

回答

4

如果你想修改弹出函数内部开始的指针,你需要通过不只是一个指针,而是一个指针的指针,这样你不仅可以修改指向数据,但指针本身。所以,你的函数签名需要成为:

int pop(struct item** start) 

这将需要修改你的代码一点点,因为你需要提领一次到你开始的指针,并两次,以获得实际的数据。另外,将起始指针设置为空将清除整个列表。您必须将开始指针设置为列表中的下一个项目。你的功能最终会看起来像这样:

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()给你原来的指针的指针,因为你会失去记忆。