【发布时间】:2015-11-22 16:06:40
【问题描述】:
我有一个函数可以从文件中读取大量单词并将它们存储在链接列表中。其结构是:
typedef struct node {
char * word;
int wordLength;
int level;
struct node * parent;
struct node * next;
} Node;
在这个函数中,我有 Start->word 和 Current->word 指向列表中的第一个单词。然后,循环浏览文件中的其余单词,将它们存储到 Current。我想保留 Start,指向列表的开头,但是,当我在函数末尾打印出 Start->word 的值时,它的值已更改为文件流中的最后一个单词。如果我静态分配 Node->word 和 currentWord 的最大长度,则此代码可以正常工作,但是,该代码旨在不对最大字长做出任何假设。 这是函数:
Node * GetWords(char * dictionary, Node * Current, int * listLength, int maxWordLength)
{
Node * Start = (Node *)malloc(sizeof(Node));
FILE *fp;
char * currentWord = (char *)malloc(maxWordLength * sizeof(char));
fp = fopen(dictionary, "r");
ErrorCheckFile(fp);
if((fscanf(fp, "%s", currentWord)) != EOF){
Current = Start = AllocateWords(currentWord);
}
//If I print out the value of "Start" here, it is correct.
while((fscanf(fp, "%s", currentWord)) != EOF){
Current->next = AllocateWords(currentWord);
Current = Current->next;
(*listLength)++;
}
printf("Starting: %s\n", Start->word); //If I print out the value of
//"Start" here, it is set to the same value as "Current", which is the
//last word in the file. I need to keep "Start" constantly pointing to
// the start to I can reset "Current" to the start throughout the program.
fclose(fp);
return Start;
}
这是我的 AllocateWords():
Node * AllocateWords(char * string)
{
Node * p;
p = (Node *)malloc(sizeof(Node));
if(p == NULL){
fprintf(stderr, "ERROR: Cannot allocate space...\n\n");
exit(1);
}
p->word = string;
p->level = -1;
p->parent = NULL;
p->wordLength = strlen(p->word);
p->next = NULL;
return p;
}
【问题讨论】:
-
显示函数 AllocatesWords.
-
对我来说,
Start的变化似乎很明显,因为你写了Current = Start = AllocateWords(currentWord);,所以是的,Start被修改了。 -
没有 AllocateWords 功能很难回答。此行会导致内存泄漏: Current = Start = AllocateWords(currentWord);因为你原来的开始会丢失。感觉你的 currentWord 是所有节点的同一个对象,并且将被覆盖,因此你的列表将包含所有相同的单词。
-
所有节点都指向同一个字符串。
标签: c string file pointers linked-list