Я не могу заставить свой стек работать, а также ... стек. Кажется, что это правильно соответствует, и из того, что я понимаю, функции push и pop написаны правильно (но они могут быть ошибочными).Stack not popping correct values: C
Я пытаюсь нажать 2 целых числа в стек, а затем снова вытащить их, чтобы проверить его, но он выдает то, что мне кажется, будет адресом памяти в целочисленной форме, однако это может быть не дело. В любом случае это не означает правильное значение, и я не могу найти что-либо очевидное с кодом.
Возможно, важно отметить, что всплывающие значения не меняются с помощью нескольких итераций, но я думаю, что вызов malloc в любом случае помешает этому. Я использую компилятор GNU GCC, включенный в блоки Code:.
ниже файл 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