我似乎並沒有讓我的堆棧操作以及堆棧。它似乎編譯正確,並從我所瞭解的推和彈出函數寫入正確(但他們可能是錯誤的)。堆棧沒有彈出正確的值:C
我嘗試推入2個整數到堆棧中,然後再次彈出它們以測試它,但它彈出了我看來是整數形式的內存地址,但是這可能不是案件。無論哪種方式,它不會彈出正確的值,我不能找到任何明顯的代碼。
可能很重要的一點是,彈出的值似乎沒有經過多次迭代而改變,但我認爲malloc調用會阻止這種情況。無論如何,我正在使用包含在Code:blocks中的GNU GCC編譯器。
下面是lib.c文件:
#include "defs.h"
//Initialising the stack
TopStack* initTOS()
{
TopStack* pTopStack;
pTopStack = (TopStack*)malloc(sizeof(TopStack));
return (pTopStack);
}
//Pushing an element onto the stack
void push(TopStack* ts, int val)
{
if (ts->num == 0) {
Stack* pNewNode;
pNewNode = (Stack*)malloc(sizeof(Stack));
pNewNode->val = val;
pNewNode->next = NULL;
ts->top = pNewNode;
ts->num++;
}
else if (ts->num != 0) {
Stack* pNewNode;
pNewNode = (Stack*)malloc(sizeof(Stack));
pNewNode->val = val;
pNewNode->next = ts->top;
ts->top = pNewNode;
ts->num++;
}
}
int pop(TopStack* ts)
{
if (ts->num == 0) {
printf("Can't pop, stack is empty!\n");
exit(1);
}
else {
Stack* pTemp;
int RemovedValue;
RemovedValue = pTemp->val;
ts->top = pTemp->next;
ts->num--;
free(pTemp);
return (RemovedValue);
}
}
void testStack(TopStack* ts)
{
int RemovedValue;
push(ts, 1);
push(ts, 2);
printf("the popped value was %i\n", pop(ts));
printf("the popped value was %i\n", pop(ts));
}
的結構都存儲在這裏在的defs.h:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#define MAX_EXPR 50
//struct that contains stack's element
typedef struct stack_elem {
int val;
struct stack_elem* next;
} Stack;
//struct that contains the pointer to the top of the stack
typedef struct {
int num; //num of elements in stack
Stack* top;
; //top of stack
} TopStack;
//ts=pointer to the top of stack, val=element to push
void push(TopStack* ts, int val); //push element on the stack
//prints the elements in the stack
void printStack(TopStack* ts);
// initialize the structure that will point to the top of the stack
TopStack* initTOS();
// a simple test for the stack
void testStack(TopStack* ts);
// ts=pointer to the top of stack
int pop(TopStack* ts); //returns element from top of stack
// simple parser function for RPN expressions that assumes numbers have only one digit
void parseRPN(char expr[], TopStack* st);
// empties the stack using the pop operation
void emptyStack(TopStack* ts);
// performs the operation defined by character op on the elements on top of stack
void performOp(TopStack* st, char op);
最後main.c文件:
#include "defs.h"
int main()
{
TopStack* tp;
tp = initTOS(); // initialize the top of stack structure
testStack(tp); // this function tests your stack
return EXIT_SUCCESS;
}
你在哪裏初始化ts-> num? – schil227