c - 如何将整行插入到c中的节点中?

标签 c linked-list getline

如何使用 getline() 获取整行并将其插入到链表中? 这是我的代码。我确定我是否可以将一行视为整个字符串。当我只尝试一行时,程序运行没有问题。但是当我尝试插入另一行时,它显示段错误:11。

typedef struct Node{
    struct Node *next;
    char *data;
}Node;

void insert(Node **head, char *input){
    Node *newNode = malloc(sizeof(Node));
    newNode->data = input;
    newNode->next = NULL;

    Node *cur = *head;
    if(*head == NULL){
        *head = newNode;
    }
    else{
        while(cur!=NULL){
            cur = cur->next;
        }
        cur->next = newNode;
    }
}

void Pint(Node *head){
    Node *cur = head;
    while(cur!=NULL){
        printf("%s\n", cur->data);
        cur = cur->next;
    }
    printf("\n");
}


int main(){
    Node *head = NULL;
    char *input = NULL;
    size_t len = 0;
    while(getline(&input, &len, stdin)!=EOF){   
        insert(&head, input);
        input = NULL;
    }
    Pint(head);
    return 0;
}

最佳答案

我相信段错误是当你这样做时:

    while(cur!=NULL){
        cur = cur->next;
    }
    cur->next = newNode;

由于 cur 在 while 循环之后为 NULL,因此它没有 next。

在 while 循环中,我会检查 cur->next 何时不为 null,这样当您将 newNode 分配给 cur->next 时,cur 就不会为 NULL。

这可以解释为什么第一个有效,因为它只是设置了 *head = newNode,但是当您添加下一个时会发生段错误。

关于c - 如何将整行插入到c中的节点中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144770/

相关文章:

c - 可能滥用 perf_event_open 系统调用

C 通用链表 : wrong output

java - 使用通用链表但在弹出时强制使用(cast)

c - 插入节点并按字母顺序排列

c++ - 是否可以在同一行上一个接一个地使用 cin 和 getline?

c++ - 结构的 Hexdump 没有输出正确的信息

c - 将 Fortran 多维数组传输到 C

c - 使用冒泡排序对结构数组进行排序 - 如何加速结构成员的交换

c++ - cin.getline 将字符串的开头设置为 '\0'

c++ - istream::getline() 没有得到最后一个字符?