#include<stdio.h>
#include<stdlib.h>
#define Size 10
typedef int Type;
typedef struct Que{
Type *base;
int front;
int rear;
}Que;
void Init(Que *q){
q->base = (Type*)malloc(Size * sizeof(Type));
q->front = q->rear = 0;
}
void Insert(Que *q, Type d){
if(q->front == (q->rear + 1) % Size){
printf("full\n");
exit(0);
}
q->rear = (q->rear + 1) % Size;
*(q->base + q->rear) = d;
//q->base[q->rear] = d;
}
void Delete(Que *q){
if((q->front + 1) % Size == q->rear ){
printf("empty\n");
exit(0);
}
q->front = (q->front + 1) % Size;
}
int main(){
Que q;
Init(&q);
Type d1 = 1;
Type d2 = 2;
Insert(&q, d1);
Insert(&q, d2);
printf("%d", q.base[q.rear]);
}
如果定义一个指针,再调用初始化函数,只会报错。这个新定义的指针是一个孤立指针
Que *q
Init(q);
Type d1 = 1;
Type d2 = 2;
Insert(q, d1);
Insert(q, d2);
printf("%d", q->base[q->rear]);
因此应当定义结构体,再传结构体的地址给初始化函数
Que q;
Init(&q);
Type d1 = 1;
Type d2 = 2;
Insert(&q, d1);
Insert(&q, d2);
printf("%d", q.base[q.rear]);
博客探讨了在实现循环队列时,直接定义指针并初始化可能遇到的问题,指出应使用结构体来存储指针,并传递结构体地址给初始化函数以避免孤立指针错误。
1628

被折叠的 条评论
为什么被折叠?



