数据结构,指针

时间:2016-10-31 14:21:47

标签: c pointers queue structure

我使用指针在C中创建了一个队列,我的代码工作但我无法理解指针变量rear1是如何工作的,因为每次调用函数,后面的init1都被初始化并且前面相同,前面存储起始的地址为first在重新初始化之后的时间,但它仍然保持起始地址,怎么可能。

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

/* run this program using the console pauser or add your own getch,                                         ("pause") or input loop */
struct node
{
    int data;
    struct node *next;
};

enqueue(struct node **start)
{
    struct node *front,*rear;
    if (*start==NULL)
    {
        *start=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&(*start)->data);
        (*start)->next=NULL;
        printf("%s","hello");
        front=(*start);
        rear=*start;
    }
    else
    {
        printf("%d",front->data);
        struct node *temp,*curr;
        curr=(struct node *)malloc(sizeof(struct node));
        rear->next=curr;
        rear=curr;
        rear->next=NULL;
        scanf("%d",&rear->data);
    }
}

dequeue(struct node **front)
{
    struct node *temp;
    temp=(*front);
    (*front)=(*front)->next;
    printf("%d",(temp->data));
    free(temp);
}

int main(int argc, char *argv[])
{
    struct node *start=NULL;
    enqueue(&start);
    enqueue(&start);
    enqueue(&start);
    enqueue(&start);
    enqueue(&start);
    enqueue(&start);    

    dequeue(&start);
    printf("\n");
    dequeue(&start);
    printf("\n");
    dequeue(&start);
    printf("\n");
    dequeue(&start);
    printf("\n");
    dequeue(&start);
    printf("\n");
    dequeue(&start);    

    return 0;
}

1 个答案:

答案 0 :(得分:0)

实际上,此代码不起作用,或者具有未定义的行为。

enqueue(struct node **start)
{
    struct node *front,*rear;
    if (*start==NULL)
    {
        *start=(struct node *)malloc(sizeof(struct node));
        scanf("%d",&(*start)->data);
        (*start)->next=NULL;
        printf("%s","hello");
        front=(*start);
        rear=*start;
    }
    else
    {
        printf("%d",front->data);
        struct node *temp,*curr;
        curr=(struct node *)malloc(sizeof(struct node));
        rear->next=curr;
        rear=curr;
        rear->next=NULL;
        scanf("%d",&rear->data);
    }
}

此处,定义* start时,您将curr分配给rear->next,但rear未定义。你有两个解决方案:

  • 使用后置作为静态变量(这显然不是一个好的解决方案,特别是如果你想使用多个队列)
  • 在您的主要StartEnd中使用2结构。

我认为您使用frontrear就好像它们是静态的一样,但默认情况下,变量&#34;会消失&#34;在声明它的函数的末尾。每次调用函数时它都是一个新的未定义变量。