//环形队列
// 不知道 哪里不对 了
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define max 10
typedef struct Queue {
int current;
int store[max];
int* begin, * end;
}queue;
queue init(void);//初始化
void push(queue*);//入队列
void pop(queue*);//出队列
void show(queue);//遍历队列元素
int main(void) {
queue army = init();//初始化一个链表
push(&army);//此后几行是调试 ,结构发现错误了
push(&army);
push(&army);
pop(&army);
show(army);
return 0;
}
queue init(void) {
queue temp;
temp.current = 0;//现在的元素个数是0
temp.begin = temp.store;//两个指针都指向 数组
temp.end = temp.store;
return temp;
}
void push(queue* temp) {
if (temp->current == max) {//数据存放满
puts("队列已满,无法入队列");
exit(-1);
}
puts("请输入要入队列的数据");
int income;
scanf_s("%d", &income);
*(temp->end)++ = income;// 在 end 位置写入 数据,然后end指针后移一位
printf("%d已入队列\n", *(temp->end - 1));
temp->current++; //队列数据 +1
if (temp->end == &(temp->store[max])) {//如果越界
temp->end = &(temp->store[0]);//指向开头位置
}
}
void pop(queue* temp) {
if (temp->current == 0) {
puts("队列为空,无法出队列");
exit(-1);
}
printf("%d已出队列", *(temp->begin)++);//begin指针读取数字, 然后 后移一位
temp->current--;
if (temp->begin == &(temp->store[max])) {//如果越界
temp->begin = &(temp->store[0]);//指向开头位置
}
}
void show(queue temp) {
printf("temp.current is %d\n", temp.current);
while(temp.current != 0) {
if (temp.begin != temp.store) {
printf("--%d--", *(temp.begin));
temp.begin++;
}
temp.current--;
}
}
![](https://profile-avatar.csdnimg.cn/1b53c80bbc13450daf38c013f550ac12_beabonnymiaomiao.jpg!4)
环形队列使用指针导致错误了
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- X-道至简 2022-10-07 21:06关注
这个init是不对的, 如果返回一个形参 begin和end的值会乱掉的,只是值拷贝。 要malloc返回一个地址
queue army = init(); 这句话运行后会产生一个先的变量,地址是改了的。
先把这个改了试试queue init(void) { queue temp; temp.current = 0;//现在的元素个数是0 temp.begin = temp.store;//两个指针都指向 数组 temp.end = temp.store; return temp;
main函数这样改了一下输出好像对了
int main(void) { //queue army = init();//初始化一个链表 queue army; army.current = 0;//现在的元素个数是0 army.begin = army.store;//两个指针都指向 数组 army.end = army.store; push(&army);//此后几行是调试 ,结构发现错误了 push(&army); push(&army); pop(&army); show(army); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 metadata提取的PDF元数据,如何转换为一个Excel
- ¥15 关于arduino编程toCharArray()函数的使用
- ¥100 vc++混合CEF采用CLR方式编译报错
- ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
- ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
- ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
- ¥50 如何openEuler 22.03上安装配置drbd
- ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
- ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
- ¥15 Windows11, backspace, enter, space键失灵