Home > Blockchain >  Why am I getting an error when I try to use push and pop function?
Why am I getting an error when I try to use push and pop function?

Time:03-14

The question asks us to "Write the program by completing the main function that calls the push function at least three times, then prints out the updated stack, then calls the pop function and prints out the updated stack again."

The code tells me that the compilation failed due to the following reasons: Line 10 | { Which to me does not make sense. I tried removing it but it gives other errors

Additionally, the code gives a warning saying " warning: array ‘stack’ assumed to have one element" Which I have no idea what that means.

This is the code:

#include <stdio.h>
#define STACK_EMPTY '0'
#define STACK_SIZE 20

char stack[], item;
int *top, max_size;

void
push(char stack[], char item, int *top, int  max_size),
{
     if (*top < max_size-1) 
     {
         --(*top);
         stack[*top] = item;
     }
}

char
pop (char stack[],    /* input/output - the stack */
    int *top)        /* input/output - pointer to top of stack */
{
    char item;       /* value popped off the stack */

    if (*top >= 0) 
    {
        item = stack[*top];
        --(*top);
    } 
    else 
    {
         item = STACK_EMPTY;
    }

    return (item);
}

int
main (void)
{
   char s [STACK_SIZE];
   int s_top = -1; // stack is empty

   if (*top <= -1)
{
    item = STACK_EMPTY;
}
   return (0);
}

CodePudding user response:

Issue is in how you are handling the top pointer. you decrement the pointer i.e., --top, NOT the value pointed by it. Also push should increment it i.e., top.

---Here is the corrected code ----


#include <stdio.h>
#define STACK_SIZE 20
#define STACK_EMPTY '0'

char item;
int top_idx = 0;

void
push(char *stack, char item)
{
     if (top_idx < STACK_SIZE) 
     {
        stack[top_idx] = item;
        top_idx  ;
     }
}

char
pop (char *stack)        /* input/output - pointer to top of stack */
{
    char item;       /* value popped off the stack */

    if (top_idx >= 0) 
    {
        top_idx--;
        item = stack[top_idx];        
    } 
    else 
    {
         item = STACK_EMPTY;
    }

    return (item);
}

int
main (void)
{
   char s [STACK_SIZE];

   push(s,'a');
   push(s,'b');

   printf("Pop = %c \n",pop(s));
   printf("Pop = %c \n",pop(s));
   
   

   return 0;
}

CodePudding user response:

The error regarding "stack assumed to have one element" is because you put no number between the square brackets char stack[];. I suspect you meant

char stack[STACK_SIZE];
  • Related