C++ 列表字符获取问题,内存分配错误?

标签 c++ string list tail head

这是我的结构

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/

相关文章:

c++ - 如何在类中传递函数作为参数?

c++ - 为什么SFML Shader会导致segmentation fault?

string - 检查字符串是否以 Lua 中的特定模式开头和结尾

python - 将 Counter() 列表附加到 pygtk 树存储 (Python)

c++ - 为什么未初始化的 const 成员在 C 中的处理方式与在 C++ 中的处理方式不同?

c++ - c++标准库的设计原则是什么?

javascript - 通过在 Javascript 中旋转字符串来打印所有可能性

javascript - 如何从Jquery中的字符串中提取子字符串

python - 如何在 Python 中使用循环反转列表的一部分?

c - 对链表进行排序的最佳方法是什么?