【发布时间】:2020-06-16 16:42:55
【问题描述】:
我正在编写一个队列数据结构,一旦值返回到堆栈中,我就无法将整数的值保留在数组中。 pop 函数正在做它需要做的事情,但为什么 main 没有得到这些信息?我错过了什么? malloc?
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
int QUE[20];
const int EMPTY = -1;
int position = -1;
int retrieve = 0;
//push, append to front of array
bool push(int num) {
if (position >= 20) return false;
position += 1;
QUE[position] = num;
return true;
}
//pop from top of array
bool pop() {
if(QUE[retrieve] == 0) return false;
int hold = QUE[retrieve];
printf("%d",hold);
retrieve ++;
return hold;
}
// PEEK
// First in first out
int main() {
push(12);
push(90);
push(22);
int t;
//why does pop equal 1
while ((t = pop()) != 0) {
printf("t = %d\n",t);
}
}
【问题讨论】:
-
true 被解释为值 1。
-
您在
push()中还有一个错误:当position == 19进入时,您将写入QUE[20],这是超出范围的。而且您在pop()中对retrieve进行无限制检查。 -
我明白了,谢谢。另外,我很困惑为什么这个问题被否决了。有人知道吗?
标签: c boolean queue implicit-conversion