The program is an Array Based Queue I am attempting to program.
The puzzling output I am getting is:
Enqueuing 500
4199136 500
I cannot figure out why 4199136 is outputting, after the space in the Output function.
I know it is some sort of memory/array management issue I am making, but I can find the flaw. Any insight would be much appreciated.
The code is posted below in its entirety.
#include <iostream>
#include <iomanip>
#include <array>
#define MAX_SIZE 10
using namespace std;
class ABQ
{
private:
int a[MAX_SIZE];
int count, front, back;
public:
ABQ()
{
front = -1;
back = -1;
count = 0;
}
bool IsEmpty()
{
return(front == -1 && back == -1);
}
bool IsFull()
{
return (back + 1) % MAX_SIZE == front ? true : false;
}
void Enqueue(int n)
{
cout << "Enqueuing " << n << endl;
if(IsFull())
{
cout << "Array Based Queue is FULL" << endl;
return;
}
else
{
back = (back + 1) % MAX_SIZE;
}
a[back] = n;
}
void Dequeue()
{
if(IsEmpty())
{
cout << "Array Based Queue is EMPTY" << endl;
return;
}
else if(front == back)
{
back = front = -1;
}
else
{
front = (front + 1) % MAX_SIZE;
}
}
int Front()
{
if(front == -1)
{
{
return -1;
}
return a[front];
}
return 0;
}
void Output()
{
count = (back + MAX_SIZE - front) % MAX_SIZE + 1;
for(int i = 0; i < count; i++)
{
int index = (front + i) % MAX_SIZE;
cout << a[index] << " ";
}
cout << endl << endl;
}
};
int main()
{
ABQ Q;
Q.Enqueue(500);
Q.Output();
return 0;
}
It's partly because your initial values for front
and back
are out of range for your array indexes, and partly because you don't handle front
correctly.
After the call to Enqueue(500)
, front
will still be -1
and back
will be 0
. When you call Output
, this will output two values, one at a[-1]
, which is Undefined Behavior, and the other at a[0]
.
Your Output
function (and possibly other places) needs to not consider the value at a[front]
as a valid element of the array.