Search code examples
cmultidimensional-arraystackc-stringsfunction-definition

How to use a stack(array) for strings instead of characters or integers in c?


#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?


Solution

  • 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;
    }