【发布时间】:2015-06-04 00:21:30
【问题描述】:
我正在尝试从文件中读取数据并将数据保存到链接列表中。我们无法将 char 字变成静态字符。我们必须使用 char *word 使其动态地接受任意长度的单词。我无法从文件中读取单词并将其保存到动态字符中。我以前用静态字符做过这件事,这很容易。这是代码。
#include <stdio.h>
#include <stdlib.h>
struct node {
char *word;
struct node *next;
};
struct codex {
char *word;
struct codex *next;
};
struct node *loadWords(FILE *stream);
int main() {
struct node *head;
FILE *stream;
head = loadWords(stream);
return 0;
}
struct node *loadWords(FILE *stream) {
struct node *poem;
struct node *temp;
char *words, *currentWord;
size_t chrCount;
stream = fopen("hw8.data", "r");
rewind(stream);
while(!feof(stream)) {
if(temp = (struct node*)calloc(1, sizeof(struct node)) == NULL) {
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
getline(&words, &chrCount, stream);
currentWord = strtok(words, " ");
strcpy(temp->word, words);
head->next = temp;
head = head->next;
}
return poem;
}
我如何动态地做到这一点?
【问题讨论】:
标签: c dynamic linked-list char