我正在编写一个Queue数据结构,并且一旦在堆栈中返回该值,便无法在数组中保留整数值。弹出功能完全在做它需要做的事情,但是为什么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);
}
}
答案 0 :(得分:2)
您正试图在相同的值内传递两种不同的信息-布尔状态“弹出成功”和从队列弹出的整数。那很糟;并且不匹配导致您将返回类型声明为bool
,这导致t
的结果值为零或一(作为false
或true
的转换,分别为int
类型。
尝试将操作分为测试和提取阶段,例如:
bool anyItemInQueue()
{
return _add_appropriate_condition_here_;
}
int main()
{
....
while( anyItemInQueue() )
{
int t = pop();
.... // use t here
}
}
或传递另一个变量以接收另一个值:
bool pop(int *result)
{
if( anyItemInQueue() )
{
*result = QUE[retrieve];
.... // some housekeeping here
return true; // success status
}
return false; // failure status
}
int main()
{
....
int t;
while( pop( & t ) ) // point at t to receive the popped value
{
.... // use t here
}
}
答案 1 :(得分:1)
这是因为任何非零值都将转换为bool
true ,然后再转换为整数。 bool
true 的整数值为 1
答案 2 :(得分:1)
您的代码具有未定义的行为。
例如考虑功能push
//push, append to front of array
bool push(int num) {
if (position >= 20) return false;
position += 1;
QUE[position] = num;
return true;
}
为简单起见,我们假设数组QUE
仅具有一个声明为的元素
int QUE[1];
在这种情况下,由于数组的容量,队列只能包含一个推入值。
因此,像
这样的push
首次调用之后
push( 0 );
您将拥有position
等于0
,并且队列包含值0
。
例如第二次调用该函数
push( 1 );
函数中的条件
if (position >= 1) return false;
的计算结果为true,因为position
的当前值为0
。结果,该函数将尝试将值1
写入数组QUE[1]
的无效位置。
该数组仅包含一个元素,但是该函数允许再写入一个元素。
现在让我们考虑函数pop
bool pop() {
if(QUE[retrieve] == 0) return false;
int hold = QUE[retrieve];
printf("%d",hold);
retrieve ++;
return hold;
}
,并且同一队列中仅包含一个等于0
的元素(请参阅上一个调用push( 0 )
)。
if语句的条件
if(QUE[retrieve] == 0) return false;
评估为true(队列确实包含早先在队列中推入的值0),然后该函数将返回false,就好像该队列是空的,尽管它不是空的。
因此,此功能无效。
此外在主循环中
while ((t = pop()) != 0) {
printf("t = %d\n",t);
}
似乎您正在尝试输出存储在队列中的值。但是,该函数不会返回此类值。由于返回类型bool
是C标准类型_Bool
的typedef,因此任何返回值都将转换为0
或1
。
所以程序完全错误。