【发布时间】:2021-01-17 20:46:28
【问题描述】:
我正在使用链表来实现堆栈,因为它是在大学里给我们的,但我无法消除分段错误,因为我对分段错误不太了解。我把我的代码放在这里。请告诉我的错误和原因,以免再犯这个错误_/_
#include <stdio.h>
#include <stdlib.h>
struct node { int data; struct node *next; };
struct node *top = NULL;
//push function representation
void push (int x) {
struct node*newnode;
newnode = (struct node *) malloc (sizeof (struct node));
newnode->data = x;
newnode->next = top;
top = newnode;
}
//traverse function representation
void traverse ()
{
struct node*temp;
temp = top;
if (top == NULL)
{
printf ("Stack is empty, please push some element");
}
else
{
while (top != NULL)
{
printf ("The element(s) in Stack are %d", temp->data);
temp = temp->next;
}
}
}
//peek function representation
void peek ()
{
if (top == NULL)
{
printf ("Stack is empty");
}
else
{
printf ("Top element is %d", top->data);
}
}
//pop function representation
void pop ()
{
struct node *temp; temp = top;
if (top == NULL)
{
printf ("This is underflow condition");
}
else
{
printf ("%d", top->data);
top = top->next;
free (temp);
}
}
void main ()
{
push (2);
push (4);
traverse ();
peek ();
pop ();
}
【问题讨论】:
-
使用调试器。至少它会立即告诉您哪一行代码触发了段错误。这是您自己调试所需的最少信息,应在此处提供。您还可以使用调试器单步调试代码并在运行时检查状态。
-
由于我对调试器了解不多,请您告诉我必须使用哪个调试器才能获得最佳结果?
-
谷歌一下。这取决于您使用的操作系统。如果是 Linux,那么
gdb很常见。
标签: c data-structures linked-list stack