gpt4 book ai didi

c - 使用 scanf 将标准输入解析为链表

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:04 24 4
gpt4 key购买 nike

我想获取一个由 3 个分号分隔的标准输入(例如:test1:127:completed),并将其放入包含 3 个属性的链表的节点中。当我运行它时它给了我一个段错误,我是否在第 96 行不正确地使用了 scanf?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 1024

//for the linked list
struct node{
char *fileName;
int *lineNumber;
char *filler;
struct node *next;
};

int main (int argc, char *argv[])
{
//Create the linked list of the file location and the line number
char tmpstring[BUFFERSIZE];
/* This won't change, or we would lose the list in memory */
struct node *head = NULL;
//tail
struct node *tail = NULL;
/* This will point to each node as it traverses the list */
struct node *ptr;
//new node pointer
struct node *newnode;

while (fgets(tmpstring, 128, stdin) == tmpstring)
{
newnode->next = NULL;
// First insertion is a special case.
if (tail == NULL)
head = tail = newnode;
else {
tail->next = newnode;
tail = newnode;
}
} // while

for (ptr = head; ptr != NULL; ptr = ptr->next)
//THIS IS THE PROBLEM scanf(" %s:%d:%s", ptr -> fileName, ptr -> lineNumber, ptr -> filler);
printf("%s", ptr->fileName);

//get how many nodes are in the linked list
struct node *tmp = head;
int count = 0;
while(tmp!=NULL)
{
count++;
tmp = tmp->next;
}
//end list creation

//getGrepOutput();
printf("%d\n", count);
}

//new code added
ptr -> fileName = (char*) malloc(50);
ptr -> lineNumber = (int*) malloc(50);
ptr -> filler = (char*) malloc(50);

最佳答案

scanf(" %s:%d:%s", ptr -> fileName, ptr -> lineNumber, ptr -> filler);

您需要为 ptr -> fileName 分配内存,这只是您程序中的悬空指针。 lineNumberfiller 成员也是如此。

关于c - 使用 scanf 将标准输入解析为链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com