Jack is Back

stack of clothes

Suppose that a stack for numbers is declared in C, per the below:

const int CAPACITY = 50;

typedef struct
{
    int numbers[CAPACITY];
    int size;
}
stack;

Suppose, too, that one such stack, s, has been defined globally, per the below:

stack s;

And that it’s been initialized in main, per the below:

s.size = 0;

Recall that “push” means to add a number to the “top” of s.

  1. (3 points.) In test/jack/push.c, complete the implementation of push, below, in such a way that the function pushes n onto s, returning true if successful. If the stack is already full, the function should instead return false.

     bool push(int n)
     {
         // TODO
     }
    

Recall that “pop” means to remove and return the “top” (i.e., most recently pushed) number from s. Consider the incomplete implementation of pop, below. It, too, is meant to return true if successful and false if not.

bool pop(int *n)
{
    // TODO
}
  1. (2 points.) In no more than two sentences, when should pop return false?

  2. (2 points.) Why does pop take the address of an int as its argument rather than an actual int?

  3. (3 points.) In test/jack/pop.c, complete the implementation of pop, above, in such a way that the function pops the top number from s.


Suppose that a stack is instead declared per the below:

typedef struct
{
    int *numbers;
    int size;
}
stack;

And suppose that one such stack, t, has been defined globally, per the below:

stack t;

And that it’s been initialized in main, per the below:

t.numbers = NULL;
t.size = 0;
  1. (3 points.) In test/jack/push2.c, complete the re-implementation of push, below, in such a way that the function pushes n onto t, returning true if successful, allocating more memory for t.numbers as needed. If sufficient memory cannot be allocated, the function should instead return false.

     bool push(int n)
     {
         // TODO
     }