【问题标题】:Data structure, pointers数据结构,指针
【发布时间】:2016-10-31 14:21:47
【问题描述】:

我在 C 中使用指针创建了一个队列,我的代码可以工作,但我无法理解指针变量 back1 是如何工作的,因为每次调用函数时,rear1 都会被初始化,并且与 front 相同,front 存储 start 的地址为 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;
}

【问题讨论】:

  • 首先,请尝试重新格式化您的代码以使其可读。
  • 如果使用正确的标点符号和可能超过一个的句子,你的问题会更清楚。
  • 请重新表述您的问题,我(可能还有大多数其他读者)不明白问题所在。
  • 继续你的程序根本不应该工作。当您使用未初始化的局部变量时,enqueue 函数至少包含一种 未定义行为 的情况。在第一次通话后,您并没有真正将任何东西链接到队列中。
  • 并请正确格式化您的代码(例如,在您的 C 教科书中完成的方式)。

标签: c pointers queue structure


【解决方案1】:

实际上,这段代码不应该工作,或者有未定义的行为。

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-&gt;next,但 rear 未定义。您有 2 个解决方案:

  • 将后部用作静态变量(这显然不是一个好的解决方案,尤其是在您想使用多个队列时)
  • 在主结构中使用 2 个结构,StartEnd

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多