Nishant Baruah
Nishant Baruah

Reputation: 11

If I write 'endl' at the line then I am not able to get the right output, but if I don't write 'endl' at the end then I get the right output. Why?

#include <iostream>

using namespace std;

struct stack
{
    int size;
    int top;
    int *arr;
};

int isEmpty(struct stack *ptr)
{
    if (ptr->top == -1)
    {
        return 1;
    }
    else
    {
        return 0;    
    }
}

int isFull(struct stack *ptr)
{
    if (ptr->top == ptr->size - 1)
    {
        return 1;
    }
    else
    {
        return 0;    
    }
}

int main()
{
    struct stack *s; 
    s->size = 80;
    s->top = -1;
    s->arr = (int *)malloc(s->size * sizeof(int));  
    // s->arr = new int[s->size];

    //check if the stack is empty
    if (isEmpty(s))
    {
        cout<<"The stack is empty";   
    }
    else
    {
        cout << "The stack is not empty";
    }

    return 0;
}

Above is the code where I have not written endl under the if cout statement, but if I write it then I do not get the required output as:

"The stack is empty"

Upvotes: 1

Views: 56

Answers (1)

kiner_shah
kiner_shah

Reputation: 4681

The problem in your code is that you are not initializing your stack. You should allocate some memory to stack object. But, then you will have to check in your functions if stack is nullptr, before accessing its contents.

It's better to create a class for Stack and make all the functions members of this class. Also, you can use bool data type for returning from isEmpty() and isFull and new/delete operators instead of malloc.

#include <iostream>

using namespace std;

class Stack
{
    int size;
    int top;
    int *arr;
public:
    Stack(int size_) : size(size_), top(-1) {
        arr = new int[size];
    }
    ~Stack() {
        delete[] arr;
    }
    bool isEmpty() {
        return top == -1;
    }
    bool isFull() {
        return top == size - 1;
    }
};

int main()
{
    Stack *s = new Stack(80);

    //check if the stack is empty
    if (s->isEmpty())
    {
        cout<<"The stack is empty";   
    }
    else
    {
        cout << "The stack is not empty";
    }
    
    delete s;

    return 0;
}

Upvotes: 1

Related Questions