【问题标题】:Dynamic queue implementation动态队列实现
【发布时间】:2013-09-27 16:35:29
【问题描述】:

我是链表的新手。每次我编写代码时都会出现运行时错误。与此相同,我在该程序中也遇到运行时错误。请解释代码中的错误。我试图找出错误,但对我来说一切似乎都很好。请解释。

# include <iostream>
using namespace std;
struct node
{
    int a;
    struct node *next;
};
typedef struct node node;
node *front = NULL;
node *rear = NULL;
void enqu(int b)
{
    node *p;
    p->a = b;
    if(front == NULL)
    {
        p->next = NULL;
        front = p;
        rear = p;
    }
    else
    {
            p->next = NULL;
        rear->next = p;
        rear = p;
    }
}
void dequ()
{
    node *p;
    if (front != NULL)
    {
        if(front == rear)
        {
        front = NULL;
        rear = NULL;
        }
        else
        {
            front=front->next;
        }
        cout<<"no deleated is"<<p->a<<"\n";
    }
    else
    {
        cout<<"queue is empty";
    }
}
void display()
{
    node *p;
    if(p!=NULL)
    {
        p=front;
    while(p!=NULL)
    {
        cout<<p->a;
        p=p->next;
    }
    }
    else
    {
        cout<<"queue is empty";
    }
}
int main()
{
    enqu(1);
    enqu(2);
    enqu(5);
    enqu(6);
    enqu(7);
    enqu(8);
    display();
    dequ();
    dequ();
    display();
    return 0;
}

【问题讨论】:

  • 你用过调试器吗?
  • 是的,它没有显示任何编译错误它显示的是运行时错误
  • 调试器用于运行时而不是编译时
  • 您好,欢迎您!如果您发布这样的问题,它确实有助于说明(在问题中)您的预期输出是什么,以及实际发生了什么。那么,您遇到了什么 运行时错误?您使用的是 gcc、Visual Studio 还是其他什么?

标签: c++ queue


【解决方案1】:

修改未分配的指针是未定义的行为。

void enqu(int b)
{
    node *p;
    p->a = b;
    ^^^^^^^^^

您应该使用node *p = new node; 分配内存,并在某处使用delete

void display()
{
    node *p;
    if(p!=NULL)
    {
        p=front;
        ^^^^^^^^

或者,将p 设置为有效的分配点。例如node *p = front;

你应该阅读很多来学习 C++,阅读:

  • 裸指针 (new/delete)
  • 智能指针(std::unique_ptrstd::shared_ptr、...)
  • STL 容器(std::liststd::vector、...)
  • 尝试阅读 StackOverflow 中关于 C++ 的讨论

【讨论】:

  • 我没有得到它请进一步解释..它的解决方案是什么..?
  • @user2177859:忽略内存泄漏,here 是一个工作代码作为起点...
猜你喜欢
  • 2012-06-24
  • 2018-06-28
  • 2014-09-03
  • 2016-09-10
  • 1970-01-01
  • 2018-01-22
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多