1
#include <stdio.h>
#include<string.h>

int top = -1, n;
char stk[25][25];

int stackempty()
{
    if ( top == -1 )
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int stackfull()
{
    if ( top == n )
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void push( char a[] )
{
    if ( !stackfull() )
    {
        top++;
        strcpy( stk[top], a );
    }
    else
    {
        printf( "Stackfull" );
    }
}

void pop( char a[] )
{
    if( !stackempty() )
    {
        strcpy( a, stk[top] );
        top--;
    }
    else
    {
        printf( "Stackempty" );
    }
}

int main()
{
    char o[50], n = 25;
    push( "Hello World!" );
    push( "Hello World!!!" );
    pop( o );
    printf( "%s", o );
    return 0;
}

I have created a 2D array and I am treating it as stack. I pushed two strings in the stack (Hello World! and Hello World!!!) and popped the string at top but it is printing stackfullHello World! instead of printing Hello World!!!. Is there any other way of implementing this or any correction in my approach to it?

1 Answer 1

2

You have an uninitialized variable n in the file scope

int top=-1,n;

Within main you declared another local variable n

char o[50],n=25;

So the variable n declared in the file scope stays unchanged.

At least you need to initialize the global variable like

int top=-1,n = 25;

and remove the local declaration of n

char o[50];

Pay attention to that the function stackFull is incorrect. The stack is full when top is equal to n - 1 because initially top is equal to -1.

So define the function like

int stackfull( void )
{
    return top == n - 1;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.