[英]Why is this static queue program not working? It ends on its own, abruptly
bool queueIsFull(int rearPointer)
{
if(rearPointer==9)
return 1;
else
return 0;
}
void PUSH (int queue[], int value, int *frontPointer, int *rearPointer)
{
*rearPointer++;
if(*frontPointer==-1)
*frontPointer=0;
queue[*rearPointer] = value;
}
bool queueIsEmpty (int frontPointer, int rearPointer)
{
if(rearPointer==(-1) && frontPointer==(-1))
return true;
else
return false;
}
void POP (int* frontPointer, int* rearPointer, int queue[])
{
cout << "\n Deleted element is: " << queue[*frontPointer];
if(*rearPointer==*frontPointer)
{
*rearPointer=-1;
*frontPointer=-1;
}
else
*frontPointer++;
}
int main()
{
int option, value, queue[10];
int rearPointer=-1, frontPointer=-1;
while(1)
{
cout << "\n----------[STATIC QUEUE]--------\nEnter a choice: \n1. PUSH AN ELEMENT\n2. POP AN ELEMENT\n3. EXIT\n";
cin >> option;
switch(option)
{
case 1: if(!queueIsFull(rearPointer))
{
cout << "\nEnter a value to push in queue: ";
cin >> value;
PUSH(queue, value, &frontPointer, &rearPointer);
}
else
cout << "\nqueue is full. Empty the queue elements and try again!";
break;
case 2: if(!queueIsEmpty(frontPointer, rearPointer)) // either of the parameters would do.
POP(&frontPointer, &rearPointer, queue); // queue is optional. You only need it to display thte poped value.
else
cout << "\nqueue is already empty. Enter some elements";
break;
case 3: return 0;
break;
default: cout << "\nWrong choice! Try again.";
break;
}
}
}
I can't get anywhere and I'm not able to debug the problem because the program gets terminated abruptly when I enter values in the queue! 我无法到达任何地方,我无法调试问题,因为当我在队列中输入值时,程序会突然终止! That's why it is getting difficult to understand where the root problem is!
这就是为什么很难理解根本问题在哪里! Why is it happening?
为什么会这样?
Also, can you give me some tips on how to solve such problems in the future? 另外,您能否给我一些如何在将来解决此类问题的技巧?
The PUSH
function is actually incrementing the pointer rearPointer
instead of the value it points to. PUSH
函数实际上是递增指针rearPointer
而不是它指向的值。
Change 更改
*rearPointer++;
to 至
(*rearPointer)++;
To resolve this and other similar issue, you can run the app under debugger, I think the debugger will catch the exception and you can get some clue about what's wrong. 要解决此问题和其他类似问题,您可以在调试器下运行应用程序,我认为调试器将捕获异常,您可以获得有关错误的一些线索。
If you are using IDE, you can find the menu item with similar text as "run with debugger", or you can first run the app, and attach the debugger. 如果您使用的是IDE,则可以找到类似“使用调试器运行”的文本的菜单项,或者您可以先运行该应用程序,然后附加调试器。 You can add sleep for delay to make sure you have time to attach debugger.
您可以添加睡眠以延迟,以确保您有时间附加调试器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.