What happens in the array when functions enqueue and dequeue are performed in the queue?

Asked 1 years ago, Updated 1 years ago, 333 views

#include<stdio.h>
#define MAX4
void enquene(char*Q, charx);
char queue (char*Q);
void initialize (char*Q);
intempty (char*Q);
int head = 0;
intail = 0;
int number = 0;
void enqueue(char*Q, charx){
    if (number <MAX) {
        number++;
        tail=(tail%MAX)+1;
        Q[tail] = x;
    }
    else{
        printf("Queue Q is overflows.\n");
    }
}
char queue (char*Q) {
    if(number>0){
        number --;
        head=(head%MAX)+1;
        return(Q[head]);
    }
    else{
        printf("Queue Quality.\n");
        return('0');
    }
}
void initialize (char*Q) {
    inti;
    head = 0;
    tail = 0;
    number = 0;
    for(i=0;i<MAX;i++){
        Q[i] = '\0';
    }
}
intempty(char*Q){
    if(number==0){
        return(1);
    }
    return(0);
}
int main(void){
    charx;
    char Q [MAX];
    enqueue(Q, 'a');
    enqueue(Q, 'b');
    enqueue(Q, 'c');
    x = dequeue(Q);
    x = dequeue(Q);
    enqueue(Q, 'd');
    x = dequeue(Q);
    enqueue(Q, 'e');
    while(!empty(Q)){
        printf("%c", queue(Q));
    }
    printf("\n");
    return(0);
}

c

2022-09-30 22:02

1 Answers

First, the contents of the queue that should be in each queue/enqueue process in the main function are summarized as follows:
What should be in the queue per queue/enqueue process
 Therefore, I think the expected output is "de", but I understand that I wrote the question because I couldn't output it as expected.
 I think the reason why the output was not as expected was because I made out-of-array references in Q[tail] and Q[head].
 The following is a summary of the tail and head values after executing the queue and enqueue in the source code presented for the action in main:
tail and head values
 Therefore, the size of the array is 4 and the array is Q[0] to Q[3], but the head tail can be 4 respectively, so you can see that the reference is out of the array.
 This is due to an error in the "tail=(tail%MAX)+1;" and "head=(head%MAX)+1;" parts.
 "If you modify each to ""tail=((tail+1)%MAX);"" and ""head=(head+1)%MAX);"", the result should be as expected."


2022-09-30 22:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.