So I’ve got this code already: http://pastebin.com/3wuFNWGA
And I’ve got these typedefs in a .h file: http://pastebin.com/JTG9XHvW
I need my push function to add a node to my_stack by allocating memory for the node, storing the data (new element) in the node, and inserting the node at the top of the stack. The code runs but when I try to print the value in my_stack->top->data after pushing a new value onto the stack, it always prints zero and not the element I supposedly pushed onto the stack.
For the life of me, I can’t figure out why. I don’t think there’s a problem arising when I create the new node and store the value in data so I’m thinking there’s a problem when I try to make my_stack->top point to the most recently added node?
This is also my first post on Stack Overflow. I hope I did everything right.
Here’s the push function to push a value onto the stack:
void push( Stack *my_stack, int newElement ) {
Node_s *newNode;
newNode = (Node_s *) malloc(sizeof(Node_s));
if( newNode == NULL ) {
printf("Error: malloc failed in push\n");
exit(EXIT_FAILURE);
}
newNode->data = newElement;
newNode->next = my_stack->top;
my_stack->top = newNode;
}
Your code will print zero for the size of the stack as you never increase that.
Also it prints 0 for the element because the type of the data field is declared as
doublebut you print it with integer specificator.Changing:
to
Fixes this problem.