user11231270
user11231270

Reputation:

How to push elements in a stack using C

I tried to learn a stack in C. But unable to do the push operation as it shows some errors in it. There is no error message shown in the console. But when running the code, it shows a wrong top value when executing the peek method.

#include<stdio.h>
#include<stdlib.h>
#define MAX 50
typedef enum{FALSE,TRUE} boolean;
typedef struct stack{
    int top;
    int a[MAX];
 }stack;
void CreateStack(stack s){
    s.top = -1;
 }
 boolean isEmpty(stack s){
    return (s.top == -1);
}
boolean isFull(stack s){
    return(s.top == MAX - 1);
}
void push(stack s, int data){
    if(isFull(s)){
        printf("Stack is Full\n");
        exit(1);
    }
    else{
        s.top = s.top + 1;
        s.a[s.top] = data;
    }
 }
 void pop(stack s){
    if(isEmpty(s)){
        printf("Stack is Empty");
        exit(1);
    }
    else{
        printf("%d\n",s.a[s.top]);
        s.top = s.top - 1;
    }
 }
 int peek(stack s){
    return s.a[s.top];
 }
 void main(){
    stack s;
    CreateStack(s);
    int num;
    push(s,1);
    push(s,2);
    push(s,15);
    printf("Top value = %d\n",peek(s));
 }

Upvotes: 0

Views: 2520

Answers (1)

klutt
klutt

Reputation: 31376

The problem is that you are not modifying the struct you are passing as argument. Each function has a local copy which ceases to exist at the end of the function. Here is a sample of the push and main function. Make the same changes to all functions.

void push(stack *s, int data){
    if(isFull(s)){
        printf("Stack is Full\n");
        exit(1);
    }
    else{
        s->top = s->top + 1;
        s->a[s->top] = data;
    }
 }

void main(){
    stack s;
    CreateStack(&s);
    push(&s,1);
    push(&s,2);
    push(&s,15);
    printf("Top value = %d\n",peek(&s));
}

You could avoid pointers for isEmpty, isFull and peek since they are not modifying anything. But I thought it was easiest to have the same interface for all of them. For safety, you can declare them like bool isFull(stack const *s)

Upvotes: 2

Related Questions