0

I can't push to stack. It is how my code looks like.

    #include <stdlib.h>
#include <stdbool.h>
struct stos
{
    int data;
    struct stos *next;
};

bool add(struct stos *stack, int data)
{
    struct stos *new_element = malloc(sizeof(struct stos));
    if(NULL != new_element)
    {
        new_element -> data = data;
        new_element -> next = stack;
        stack = new_element;
        return true;
    }
    return false;

};
int main()
{
    struct stos stack;
    add(&stack,2);
    printf("Stack top data: %d\n",stosik.data);
}

Output: 69 Can someone help me to solve this problem? However if I change bool add to struct stosik *add it is working perfect. But I want to know how to change my code to bool or void type

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Coonvert
  • 3
  • 1

1 Answers1

0

For starters there is a typo

printf("Stack top data: %d\n",stosik.data);
                              ^^^^^^ 

And the semicolon after the function declaration

bool add(struct stos *stack, int data)
{
    //...
};
^^^

is redundant.

In this function

bool add(struct stos *stack, int data)
{
    struct stos *new_element = malloc(sizeof(struct stos));
    if(NULL != new_element)
    {
        new_element -> data = data;
        new_element -> next = stack;
        stack = new_element;
        return true;
    }
    return false;

};

The parameter stack is a local variable of the function that will not be alive after exiting the function. So this statement

stack = new_element;

does not make a sense.

Within main you need to declare a pointer instead of an object of the type struct stos and to initialize the pointer as a null pointer.

struct stos *stack = NULL;

In turn the function must be declared and defined the following way

bool add( struct stos **stack, int data )
{
    struct stos *new_element = malloc(sizeof(struct stos));
    if(NULL != new_element)
    {
        new_element -> data = data;
        new_element -> next = *stack;
        *stack = new_element;
        return true;
    }
    return false;
}

and called like

add(&stack,2);
printf("Stack top data: %d\n", stack->data);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335