1

Can anyone please explain here what is the issue in the below code because of that it is not producing any errors as well as any output?

    #include <stdio.h>
#include <stdlib.h>

typedef struct Stack{
        int size;
        int top;
        int data;
        int *arr;
    } Stack;

void push( Stack*s ,  int data)
    {
            s->top++;
            s->arr[s->top] = data;
    }
int main()
    {
     struct Stack *s;
     s->size = 100;
     s->top = -1;
     s->arr = (int* ) malloc (s->size* sizeof(int));
     push( s, 180);
}

1 Answers1

0

this is because you write struct Stack *s; which is just a wild pointer pointing to some space in memory with no reserved space, so you should do instead :

struct Stack *s = (struct Stack* ) malloc (sizeof(struct Stack));

to reserve space for your wild pointer.

even my compiler gave me this warning, so make sure to turn on all compiler warnings on yours.

Variable 's' is uninitialized when used here

this is the full code with only this small modification:

#include <stdio.h>
#include <stdlib.h>

typedef struct Stack{
    int size;
    int top;
    int data;
    int *arr;
} Stack;

void push( Stack*s ,  int data)
{
    s->top++;
    s->arr[s->top] = data;
}

int main()
{
    //struct Stack *s = (struct Stack* ) malloc (sizeof(struct Stack));
    struct Stack *s;
    s->size = 100;
    s->top = -1;
    s->arr = (int* ) malloc (s->size* sizeof(int));
    push( s, 180);
    printf("stack top data = %d\n", s->arr[s->top]);
}

and this is the output:

stack top data = 180
abdo Salm
  • 1,678
  • 4
  • 12
  • 22