简体   繁体   English

使用scanf将std输入解析为链接列表

[英]Parsing std input into a linked list using scanf

I want to take an std input separated by 3 semi colons (ex: test1:127:completed) and put it into a node of the linked list, which contains 3 attributes. 我想用3个半冒号(例如:test1:127:completed)分隔的std输入并将其放入包含3个属性的链表的节点中。 When I run this it gives me a segfault, am I improperly using scanf in line 96? 当我运行此命令时,它会出现段错误,是否在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);

You need to allocate memory for ptr -> fileName which is just a dangling pointer in your program. 您需要为ptr -> fileName分配内存,这只是程序中的悬挂指针。 Same for lineNumber and filler members. 同为lineNumberfiller的成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM