这是我的结构
struct list{
char c;
struct list * next;
};
我必须在这个列表中放入一个字符序列,但是当我尝试时,我总是遇到段错误
struct list * insert_list(){
//function for add a new string in the list
struct list * tmp;
string car;
int i=0, len;
cin >> car;
len=car.size();
for (i=0; i<len; i++){
tmp=new list;
tmp->c=car[i];
tmp->next=NULL;
tmp=tmp->next;
}
return tmp;
}
struct list * head(struct list *top){
//this function adds the new string on ***TOP*** of the list
struct list *tmp=NULL;
tmp=insert_list();
tmp->next=top;
return tmp;
}
struct list * tail(struct list * top){
//this function adds the new string in the ***END*** of the list
if (top==NULL){
top=insert_list();
}
else{
top->next=tail();
}
return top;
}
我认为问题出在 insert_list 函数中,我也尝试过
while(tmp->c!='\n'){
tmp=new list;
cin >> tmp->c; //also with cin.get
tmp=tmp->next;
tmp->next=NULL;
}
但我总是得到同样的错误。 我该如何解决这个问题?
最佳答案
insert_list
将始终返回 null,因此对 head
的任何调用都将出现段错误。
尝试使用结果的任何其他对 insert_list 的调用也是如此。
关于C++ 列表字符获取问题,内存分配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31165625/