I am writting this program, and I want to understand why I am getting the wrong printing (which should de 1,2,3,4,5) gives some address instead. My stackIsEmpty()
does not even act as it is meant to that is to stop printing values when the stack is empty. Here is my code:
#include <stdlib.h>
#include <stdio.h>
//Stacks using Structures and linked list and pointerws.
typedef struct Stack{
//Type of the elements of the stack. Here integers
int elem;
//To of the stack
struct Stack* previous;
} Stack;
void initialize(Stack *st);
void push(Stack *st, int element);
int pop(Stack *st);
int stackIsEmpty(Stack *st);
int main(){
int i;
Stack st;
Stack *pt_st = &st;
initialize(pt_st);
//Test phase...
for(i=0; i<5; i++)
push(pt_st, i+1);
for(i=0; i<5; i++)
printf("here is one element: %d\n", pop(pt_st));
//End of test with error!
return 0;
}
void initialize(Stack *st){
st = NULL;
}
void push(Stack *st, int element){
Stack *sta = (Stack*)malloc(sizeof(Stack));
if (sta != NULL)
{
sta->previous = st;
sta->elem = element;
st = sta;
free(sta);
}
else
exit(0);
}
int pop(Stack *st){
if(!stackIsEmpty(st))
{
printf("stack is empty cannot pop\n");
return 0;
}
else
{
int number = st->elem;
Stack* copy = st->previous;
free(st);
st = copy;
return number;
}
}
int stackIsEmpty(Stack *st){
if(st == NULL)
return 0;
else
return 1;
}