1

I try to implement a simple stack in c with pointers and struct but I think I have a problem with push or print. My program prints only the first Node.

If someone could help me to solve this

Here is my code

stack.h

/***********************************************************************
* stack.h
***********************************************************************/

#include <stdbool.h>

#ifndef _STACK_H_
#define _STACK_H_

typedef struct Stack{
    int value;
    struct Stack* next;
}Stack;

Stack initStack();

bool push (Stack* s, int n);

int pop (Stack* s);

bool stackEmpty (Stack s);

void printStack (Stack s);

#endif

stack.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "stack.h"

Stack initStack(){
    Stack s = {0, NULL};
    return s;
}

bool push (Stack* s, int n){
    if (stackEmpty(*s)){
        s->value = n;
        return true;
    }else{
        Stack stack = {n, s};
        s = &stack;
        return true;
    }
    return false;
}

int pop (Stack* s){
    int value = s->value;
    s = s->next;
    return value;
}

bool stackEmpty (Stack s){
    if (s.value == 0 && s.next == NULL)
    return true;
return false;
}

void printStack (Stack s){
    Stack* b = &s;
    printf("Stack : \n");
    while(b != NULL){
        printf("%d\n", b->value);
        b = b->value;
    }

main

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "stack.h"

int main (int argc, char** argv) {

    Stack stack1 = initStack();

    push(&stack1, 5);

    printStack(stack1);
}

1 Answer 1

1

You're taking the address of a local variable here:

Stack stack = {n, s};
s = &stack;

You need to dynamically allocate it:

Stack *stack = malloc(sizeof(*stack));
stack->value = n;
stack->next = s;
s = stack;

For consistency, I would recommend to take and return Stack * instead of Stack, and possibly rename initStack to newStack.

Sign up to request clarification or add additional context in comments.

4 Comments

I'd use the Stack* as a convention in all the methods - i.e. Pass Stack* params not Stack. Consistency will avoid confusion!
@John3136 That's what I'm recommending in the last sentence in my answer (take and return being the most important part).
@JL2210 Thanks its works perfectly ! But I don't understand why I need to use param Stack** on push and i can't use Stack*, I tried also the second case and it didn't worked... I'm a bit confused about that
@Marc No, use Stack * for everything. For example, make printStack and stackEmpty take a Stack * and make initStack return a Stack *. Just make sure to dynamically allocate memory (with malloc) in initStack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.