Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c语言中的堆栈分配空间_C_Stack - Fatal编程技术网

c语言中的堆栈分配空间

c语言中的堆栈分配空间,c,stack,C,Stack,我试图根据我的课程笔记实现一个堆栈,但我在编译时遇到了这个错误,不确定我是否正确初始化了它?我的代码在以后使用push功能时出错 更新:我现在看到双重初始化和值被分配到错误的位置 这是我的密码: struct stackelem{ char i; struct stackelem *prev; }; typedef struct stackelem Elem; struct thestack{ Elem *tp; }; typedef struct thestack S

我试图根据我的课程笔记实现一个堆栈,但我在编译时遇到了这个错误,不确定我是否正确初始化了它?我的代码在以后使用push功能时出错

更新:我现在看到双重初始化和值被分配到错误的位置

这是我的密码:

struct stackelem{
    char i;
    struct stackelem *prev;
};
typedef struct stackelem Elem;

struct thestack{
    Elem *tp;
};
typedef struct thestack Stack;

void InitialiseStack(Stack *s)
{
   Elem *e = malloc(sizeof(*e));   
   s->tp = (Elem *)calloc(1, sizeof(Elem));
   s->tp->prev = NULL;
}

void Push (Stack *s, int n)
{
   Elem *e;

   s->tp = (Elem *)calloc(1, sizeof(Elem));
   s->tp->prev = s->tp;
   s->tp->i = n;
   s->tp = e;
}
覆盖
tp
,然后尝试使其指向其旧值。除非您在以下时间之前保存,否则无法神奇地发生此情况:

Elem *e = s->tp;

s->tp = (Elem *)calloc(1, sizeof(Elem));
if (s->tp)
{
  s->tp->prev = e;
  s->tp->i = n;
}
else
{
  s->tp = e;
}

现在,如果分配失败,该函数也不会破坏堆栈的状态。

这两个函数都没有意义

void InitialiseStack(Stack *s)
{
  /* Elem *e = malloc(sizeof(*e));   */
   s->tp = (Elem *)calloc(1, sizeof(Elem));
   s->tp->prev = NULL;
}

void Push (Stack *s, int n)
{
   Elem *e;

   s->tp = (Elem *)calloc(1, sizeof(Elem));
   s->tp->prev = s->tp;
   s->tp->i = n;
   s->tp = e;
}
首先在
InitialiseStack
中有分配的内存

s->tp = (Elem *)calloc(1, sizeof(Elem));
然后在函数Push中,指针
s->tp
的值被覆盖

s->tp = (Elem *)calloc(1, sizeof(Elem));
结果导致内存泄漏。此外,每次调用函数
Push
时,指针的值都会被覆盖。同时使用未初始化的指针
e

Elem *e;
没有道理

void InitialiseStack(Stack *s)
{
  /* Elem *e = malloc(sizeof(*e));   */
   s->tp = (Elem *)calloc(1, sizeof(Elem));
   s->tp->prev = NULL;
}

void Push (Stack *s, int n)
{
   Elem *e;

   s->tp = (Elem *)calloc(1, sizeof(Elem));
   s->tp->prev = s->tp;
   s->tp->i = n;
   s->tp = e;
}
您所需要的只是以下内容

void InitialiseStack(Stack *s)
{
   s->tp = NULL;
}


e
Push()
中未初始化。你看不出来吗?我总是觉得草签有点让人困惑,我想我的老师在它被覆盖的时候浏览了一下。你能告诉我如何在push函数中初始化“e”吗?
void Push (Stack *s, int n)
{
    Elem *e = malloc( sizeof( Elem ) );

    if ( e != NULL )
    {
        e->i = n;
        e->prev = s->tp;
        s->tp = e;
    } 
}