【发布时间】:2017-10-29 00:37:39
【问题描述】:
我正在尝试使用此代码实现链接列表。此代码成功符合但导致分段错误(核心转储)错误。我该如何解决这个问题?
#include<stdio.h>
#include<stdlib.h>
struct node{
char ch;
struct node *next;
};
struct node *head=(struct node *)malloc(sizeof(struct node));
struct node *p1=NULL;
void addnode(char ch) {
if(head==NULL) {
head->ch=ch;
head->next=NULL;
}
else {
struct node *New=(struct node *) malloc (sizeof(struct node));
for(p1=head;p1->next!=NULL;p1=p1->next);
p1->next=New;
}
}
void main() {
char ch,frm,to;
printf("\nEnter the string");
while((ch=getchar())!='\0')
addnode(ch);
for(p1=head;p1!=NULL;p1=p1->next)
printf("\n%c",p1->ch);
}
【问题讨论】:
-
当你分配一个新节点时,你永远不会给它分配任何值。所以
ch是未知的,next可以指向任何地方。addnode(ch)实际上并没有使用ch的事实应该是一个警告信号...... -
罗杰那,谢谢;
标签: c string data-structures linked-list segmentation-fault