Hello. I have a question with my linked stack implementation in C. I'm pretty new to C and especially pointers. Any help will be greatly appreciated.
First of all, I tested my linked stack implementation with the following code:
From the above code, I expected the following output:Code://Just so you know typedef struct LinkedStack linkedstack; typedef struct StackNode node; struct StackNode{ char info; struct StackNode *link; }; struct LinkedStack{ struct StackNode *top; }; main(){ linkedstack s; char c; char vowels[] = "aeiou"; int i = 0; CreateStack(&s); while(i < strlen(vowels)){ push(&s, vowels[i]); i++; } while(!isEmpty(&s)){ char foo = pop(&s); printf("%s%s", &foo, "\n"); } char bar = pop(&s); }
However, the output I get looks like this: after the vowels, there will be an unwanted ascii character. When I run it from the command line, I get the clubs character. Ran from Notepad++'s NppExec plugin, I get a bar ("|").Code:u o i e a StackUnderflow occurred!
I figure that my mistake is in my implementation of push and pop (but I am heavily inclined to think that my push is perfect, that my pop is the defective one), as it messily deals with pointers. Here's my code:
Now, I've seen implementations of pop that takes in a stack pointer and a pointer to a "placeholder" i.e., to where the popped value will be stored. However, due to matters of style rooted in my OO (Java) training, I am trying to avoid that. The pop implemenations I've seen return void (as the popped element is stored in the passed pointer). I want to return a char, point blank.Code:void push(linkedstack *stack, char me){ node *NewNode; NewNode = (node *) malloc(sizeof(node)); if(NewNode == NULL){ StackOverflow(); } else{ NewNode->info = me; NewNode->link = stack->top; stack->top = NewNode; } } char pop(linkedstack *stack){ char temp; node *node; if(isEmpty(stack)){ StackUnderflow(); } else{ node = stack->top; temp = (*node).info; stack->top = (*node).link; free(node); } return temp; }
Is this possible in C or am I making myself suffer by thinking encumbered by OO? Any pointers (no pun intended) to the proper direction will be appreciated. Much thanks.