【发布时间】:2014-11-07 16:53:04
【问题描述】:
因此,我们被要求为 C 创建自己的堆栈 ADT,用于存储双精度浮点数。我用基本的堆栈函数(isEmpty、push、pop)做了一个非常基本的 ADT。无论如何,我决定通过创建 3 个变量并将它们推入堆栈来测试我的 ADT。然后我想看看最上面的元素是什么,但是我得到的输出很奇怪。
这是我收到的所有输出:
(lldb)
顶部应该指向变量结果,并打印该值,但以上就是我得到的全部。
#include <stdio.h>
#include <stdlib.h>
// create a new structure for stack ADT.
struct double_stack{
double * array;
int stackCapacity;
int numOfObjects;
int top;
};
//creating a new empty stack.
struct double_stack *newStack(){
struct double_stack* new_Stack= malloc(sizeof(struct double_stack));
//stack has a capactiy to store one element as default, and has 0 number of objects.
new_Stack->stackCapacity = 1;
new_Stack->numOfObjects = 0;
new_Stack->array = malloc(sizeof(new_Stack->stackCapacity));
//top points to -1 to show the stack is empty. When its not empty,it will point to 0,so an element can be placed at that index etc.
new_Stack->top = -1;
return new_Stack;
}
//check to see if stack is empty. Returns 1 if true. 0 if false.
int isEmptyStack(struct double_stack *this){
//if the attribute pointed in the condition below is true,then stack is empty.
if(this->numOfObjects==0 && this->top==-1){
return 1;
}
else{
return 0;
}
}
//push an element onto the stack.
void push(struct double_stack * this, double element){
this->stackCapacity++; //stack capacity is increased by 1 to make space for next element to be pushed on.
this->numOfObjects++; //number of elements increased by 1.
this->array[++this->top]=element; // the prefix ++ operator increments the top index before it is used as an index in the array (i.e., where to place the new element).
}
//this method pops an element off the stack. If stack is empty,the exit command quits the function. It returns the element to be popped ,because usually we need to perform some operation on the element.
double pop(struct double_stack*this){
if(isEmptyStack(this)){
printf("%s","Error:Cannot pop element from empty stack!");
return -1;
}
return this->array[this->top--];
}
int main() {
struct double_stack * s = newStack();
double a = 5;
double b = 10;
double result=a+b;
push(s,a);
push(s,b);
push(s,result);
printf("%d",s->top);
}
【问题讨论】:
-
malloc(sizeof(new_Stack->stackCapacity));你在里面少了一个* sizeof(double)。数组的初始分配大小正好是一个int的大小。而且由于我没有看到任何扩展算法的证据,即使你解决了这个问题,任何推送多个元素的尝试也不会奏效。 -
例如:
malloc(new_Stack->stackCapacity * sizeof(double)) -
这不会给您带来实际问题,但请考虑您的
top和numOfObjects字段似乎是多余的。最好只使用一个,这样既可以减少所需的簿记量,又可以避免出现内部不一致的可能性。