Hi everyone I am now implementing a dynamic size stack in C but get stuck in a problem... This is part of my code:
#include <stdio.h>
#include <conio.h>
typedef struct Node node;
struct Node{
int value;
node *above;
};
struct stack{
node *root;
node *top;
};
typedef struct stack stack;
void stack_init(stack *s){
s = (stack*) malloc(sizeof(stack));
s->top=-1;
s->root=-1;
printf("%d %d\n", s->top, s->root);
};
int main(){
stack s;
stack_init(&s);
printf("%d %d\n", s.top, s.root);
}
When I run the code the printf from stack_init give -1 -1 and the one from main give 70 8, while in my assumption they should be the same. What is the problem? Any help is appreciated!
mallocrather than the value the user passes in.sbuffer passed intostack_initbut rather a new buffer allocated bymalloc. Just remove themallocline and it will do what you want. One note: It's not a good idea to init pointers to-1as that is not a valid pointer value. Instead useNULL.s = (stack*) malloc(sizeof(stack));