如何将整行插入到c中的节点?
How to insert a whole line into a node in c?
如何使用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,但是当您添加下一个时会发生段错误。
如何使用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,但是当您添加下一个时会发生段错误。