【问题标题】:Best way to read line into singly linked list将行读入单链表的最佳方法
【发布时间】:2014-09-16 01:21:11
【问题描述】:

我试图弄清楚如何使用 C 实现单链表,其中节点存储指向字符串的指针(文件中的行)。我想这不会起作用,因为“line_buffer”被覆盖了,但我没有看到任何直接的解决方案。有什么想法吗?

struct line {
    char* string;
    struct line* next;
};

int main(void) {
    ...
    (open file to f)
    ...

    struct line* first = (struct line*) malloc(sizeof(struct line));
    first->string = "string0";
    struct line* current = first;

    char line_buffer[256];

    while (fgets(line_buffer, sizeof(line_buffer), f)) {
        struct line* newl = (struct line*) malloc(sizeof(struct line));
        newl->string = line_buffer;
        current->next = newl;
        current = newl;

        j++;
    }        

    current->next = NULL;

    struct line* temp = first;

    while(temp != NULL) {
        printf("%s\n", temp->string);
        temp = temp->next;
    }
}

这个输出:

string0
whatever in last line
whatever in last line
whatever in last line

【问题讨论】:

  • j++; 的意义何在? :D
  • 如果你准备好每次都 malloc 一个新的struct line,为什么你那么不愿意 malloc 一个新的缓冲区?
  • newl->string = line_buffer; --> newl->string = strdup(line_buffer);

标签: c linked-list


【解决方案1】:

您可以使用strcpy() 函数。

代替:

newl->string = line_buffer;

放:

strcpy(newl->string, line_buffer);

请注意,这只是对您的代码进行快速修复的建议,还有更好的方法来实现此逻辑。

这是great guide

您也可以编写一个简单的insert 函数来分离您的逻辑(插入到列表头部)

struct line* insertFront(struct line *head, char *string) {
    struct line *newl = malloc(sizeof(struct line));
    newl->string = (char*) malloc(strlen(string)+1);
    if(head == NULL) {           
        strcpy(newl->string, string);
        newl->next = NULL;
        head = newl;
    } else {
        strcpy(newl->string, string);
        newl->next = head;
        head = newl;
    }
    return head;
}

你会在你的代码中使用这个函数,比如:

int main(void) {
    ...
    (open file to f)
    ...

    struct line* first = NULL;    
    char line_buffer[256];

    while (fgets(line_buffer, sizeof(line_buffer), f)) {
        first = insertFront(first, line_buffer);
    }        

    struct line* temp = first;    
    while(temp != NULL) {
        printf("%s\n", temp->string);
        temp = temp->next;
    }
}

【讨论】:

  • 我需要在节点中使用指针。 // newl->string = line_buffer; memcpy(newl->string, line_buffer, strlen(line_buffer)+1);虽然会导致分段错误..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2020-08-20
  • 2018-03-17
  • 1970-01-01
相关资源
最近更新 更多