【发布时间】:2016-01-03 04:35:32
【问题描述】:
我试图在链表末尾附加一个节点,但出现分段错误。我无法弄清楚我的错误在哪里。任何帮助和建议将不胜感激!
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
}*head;
void append(int x)
{
struct node *temp1,*right;
temp1=malloc(sizeof(struct node));
temp1->data=x;
right=malloc(sizeof(struct node));
right=head;
while(right->next != NULL )
right=right->next;
right->next=temp1;
right=temp1;
right->next=NULL;
}
void print(){
struct node *temp=head;
printf("List is: ");
while( temp!=NULL )
{
printf(" %d",temp->data);
temp=temp->next;
}
printf("\n");
}
int main(){
struct node *temp;
int n,i,x;
head=NULL;//empty list;
printf("how many numbers?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nEnter the number\n");
scanf("%d",&x)
append(x);
print();
}
}
【问题讨论】:
-
head=NULL;,并且在此之后永远不会被写入..它确实从中读取,这可能是段错误。在调试器中运行它并发布回溯的输出 -
如果您没有使用调试器单步调试您的代码,则说明您没有投入足够的精力。
-
谢谢!我弄错了!
标签: c segmentation-fault singly-linked-list