灼美丽小苗苗 2022-10-07 20:29 采纳率: 55.6%
浏览 38
已结题

环形队列使用指针导致错误了

//环形队列
// 不知道 哪里不对 了
#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--;
    }
}

  • 写回答

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;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 10月16日
  • 已采纳回答 10月8日
  • 创建了问题 10月7日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度