【问题标题】:I am not able to run this code on Code::blocks IDE but works fine online...!!can anyone tell me what modifications i should to get it working on IDE?我无法在 Code::blocks IDE 上运行此代码,但可以在网上正常运行...!!谁能告诉我应该进行哪些修改才能使其在 IDE 上运行?
【发布时间】:2017-01-05 01:47:38
【问题描述】:

通过使用 typdef 我已经定义了 Stack,但是代码块给了我一个错误 当我调用对象时。

#include <iostream>
using namespace std;

struct Stack
{
    int data[20];
    int top;
};

在这个类中,Stack *s 被调用,当我运行程序时它给出一个错误,“s”可能未初始化使用。 而我已经使用构造函数对其进行了初始化。

class stackop
{
public:

    Stack *s;

    stackop()
    {
        s->top= -1; //constructor is giving error.
    }

    bool stack_empty();
    bool stack_full();
    void push();
    void pop();
    void display();
};

bool stackop::stack_empty()
{
    if(s->top == -1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

bool stackop::stack_full()
{
    if(s->top == 19)
    {
        return 1;
    }
    else
    {
        return 0;
    }
} 

void stackop::push()
{

    if(!stack_full())
    {
        s->top=s->top + 1;
        cout<<"\n Enter an element: ";
        cin>>s->data[s->top];
    }
    else
    {
        cout<<"\n THE STACK IS ALREADY FULL";
    }
}

void stackop::pop()
{
    if(!stack_empty())
    {
        cout<<"\n The value deleted or poped is "<<s->data[s->top];
        s->top=s->top-1;
    }
    else
    {
        cout<<"\n STACK IS ALREADY EMPTY";
    }
}

void stackop::display()
{
    cout<<"\n The stack is as follows...";
    for(int i=s->top; i>=0; i--)
    {
        cout<<"\n"<<s->data[i];
    }
}

此外,此代码在 cpp.sh 上运行良好,但会终止返回垃圾值的代码块的终端。

int main()
{
    int y;
    char ch;

    stackop s1;

    do
    {
        cout<<"\n 1. PUSH.";
        cout<<"\n 2. POP.";
        cout<<"\n 3. Display stack.";
        cout<<"\n\n Enter your choice :: ";
        cin>>y;

        switch(y)
        {
        case 1:
            s1.push();
            break;
        case 2:
            s1.pop();
            break;
        case 3:
            s1.display();
            break;
        }

        cout<<"\n Do you want to continue? : ";
        cin>>ch;

    } while(ch=='y');

    return 0;
}

【问题讨论】:

  • 你说,你已经初始化了成员指针s,但是你还没有。使用s-&gt;top,您将取消对 nullptr 的引用。那是UB。
  • 不是空指针。 s 根本没有初始化。

标签: c++ arrays struct constructor stack


【解决方案1】:

您正在使用未初始化的指针 (s)。

Stack *s;

stackop()
{
    s->top= -1; //constructor is giving error.
}

在这里,您正在访问内存中的一个随机位置。

也许你可以不使用指针来修复它

Stack s;

stackop()
{
    s.top= -1;
}

【讨论】:

    【解决方案2】:

    对你的程序做些小改动,它会正常工作

    Stack *s = new Stack;
    

    通过上述更改,程序可以在代码块 IDE 中运行

    【讨论】:

    • 还好,还有内存泄漏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2015-07-12
    • 2021-07-17
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多