使用相同的代码,函数中的代码会出错 [英] With the same code, code in the function make an error

查看:74
本文介绍了使用相同的代码,函数中的代码会出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我实现了一个软件堆栈,如果我直接在主函数中调用以下代码,则不会出现错误:

 typedef  struct 节点
{
     int 数据;
    结构堆栈* next;
}节点;

typedef NODE * STACK;
/*  
...有一些代码
*/
 int  main()
{
    堆栈* st;
    STACK p =(STACK)malloc( sizeof (STACK));
    p-> data =  8 ;
    如果(空(* st))
    {
        p-> next = NULL;
        * st = p;
    }
    其他
    {
         p-> next = * st;
         * st = p;
    }
} 



但是当我将上述代码放入函数中并调用该函数时,会出现运行时错误(Windows):该程序已停止工作

 typedef  struct 节点
{
     int 数据;
    结构堆栈* next;
}节点;

typedef NODE * STACK;
/*  
...有一些代码
*/
 void 推送(堆栈* st, int  )
{
    STACK p =(STACK)malloc( sizeof (STACK));
    p-> data =  8 ;
    如果(空(* st))
    {
        p-> next = NULL;
        * st = p;
    }
    其他
    {
         p-> next = * st;
         * st = p;
    }
}
 int  main()
{
    堆栈* st;
    push(st, 8 );
    
} 



谢谢大家!

解决方案

也许您需要回头思考一下变量等的工作原理.

调用push函数时,首先要做的是创建将值压入的堆栈.因此,当您第二次调用它时,您是否要将变量添加到同一堆栈或不同的堆栈中?当您pop它们时,它们将来自何处?

然后,您可以查看当您引用尚未设置的指针时发生了什么……并开始考虑堆栈应该如何工作,以及为什么它根本没有下一个指针!

Hi all,

I implemented a software stack, if I directly call below code in main function, there''s NO error:

typedef struct node
{
    int data;
    struct stack *next;
}NODE;

typedef NODE *STACK;
/*
... there are some code
*/
int main()
{
    STACK *st;
    STACK p = (STACK)malloc(sizeof(STACK));
    p->data = 8;
    if (empty(*st))
    {
        p->next = NULL;
        *st = p;
    }
    else
    {
         p->next = *st;
         *st = p;
    }
}



but when I put above code into a function and call this function, there is a run-time error (Windows): the program has stopped working

typedef struct node
{
    int data;
    struct stack *next;
}NODE;

typedef NODE *STACK;
/*
... there are some code
*/
void push(STACK *st, int value)
{
    STACK p = (STACK)malloc(sizeof(STACK));
    p->data = 8;
    if (empty(*st))
    {
        p->next = NULL;
        *st = p;
    }
    else
    {
         p->next = *st;
         *st = p;
    }
}
int main()
{
    STACK *st;
    push(st, 8);
    
}



Thank you all!

解决方案

Perhaps you need to go back a bit and think about how variables and so forth work.

When you call your push function, the first thing you ar edoing is creating the stack onto which you will be pushing the value. So when you call it a second time, are you going to add variables to the same stack, or a different one? When you pop them, where are they going to come from?

And then you can look at what happens when you reference a pointer you haven''t set yet...and start thinking about how a stack should work, and why it wouldn''t have a next pointer at all!


这篇关于使用相同的代码,函数中的代码会出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆