为什么指针 "Start" 会改变? (C)

Why is the pointer "Start" changing? (C)

我有一个函数可以从文件中读取大量单词并将它们存储在链表中。其结构是:

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;
}

您正在覆盖此行中 Start 的值:

Current = Start = AllocateWords(currentWord);

所有节点都指向同一个字符串,所以你想把函数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 = strdup(string); //get a copy of the string
  p->level = -1;
  p->parent = NULL;
  p->wordLength = strlen(p->word);
  p->next = NULL;
  return p;
}

strdup 会修复它,但出于上述原因 here

,您可能需要考虑编写自己的 strdup 副本

strdup 也可能会失败,因此您必须添加一些错误检查。

此外,正如其他用户所建议的那样,您的程序正在泄漏内存。