【发布时间】: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