【发布时间】: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