简体   繁体   中英

Linear queue implementation using C. Compiler doesn't show any error but program not running(shows error message: program has stopped working)

I am trying to implement linear queue using C but the program doesn't run even though the compiler doesn't show any error. When i try to run the program a pop up windows says "The program has stopped working". Can anyone show me what is wrong with this code and how to fix it? Any help will be appreciated. Thank you

```
#include<stdio.h>
#define MAXSIZE 30

struct queue{
    int item[MAXSIZE];
    int rear;
    int front;
};
typedef struct queue qu;

void enqueue(qu *q){
    int data;
    printf("Enter the data to be inserted(enqueued) \n");
    scanf("%d", &data);
    if(q->rear == MAXSIZE-1){
        printf("Queue is full \n");
    }
    else{
        q->rear++;
        q->item[q->rear] = data;
    }
    
}

void dequeue(qu *q){
    if(q->rear < q->front){
        printf("queue is empty \n");
    }
    else{
        q->front++;
        printf("Deleted item is \n %d \n", q->item[q->front]);
    }
}
void display(qu *q){
    int i;
        if(q->rear < q->front){
        printf("queue is empty \n");
    }
    else{
        printf("The queue is : \n");
        for( i=q->front; i<= q->rear; i++){
            printf("%d \t",q->item[i]);
            
        }
    }
}

int main(){
    int ch;
    qu *q;
    q->front = 0;
    q->rear = -1;
    printf("MENU for operation \n");
    printf("1: Enqueue \n 2: Dequeue \n 3: Display \n 4: Exit \n");
    do{
        printf("Choose an operation \n");
        scanf("%d", &ch);
        switch(ch){
            case 1:
                enqueue(q);
                break;
            case 2:
                dequeue(q);
                break;
            case 3:
                display(q);
                break;
            case 4:
                break;
            default:
                printf("Choose number from 1-4");           
        }
    }
    while(ch != 4); 
    return 0;
}

With qu *q; you define a pointer with indeterminate value to a qu object; this is of no use. Instead you've to define qu q; and write q. everywhere you wrote q-> and (&q) everywhere you wrote (q) , respectively, in main .

Then in dequeue with

        q->front++;
        printf("Deleted item is \n %d \n", q->item[q->front]);

you erroneously increment front before taking the front item from the queue; correct:

        printf("Deleted item is \n %d \n", q->item[q->front++]);

Finally note that your queue implementation could be improved by reusing released queue positions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM