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

标签 c string file pointers linked-list

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

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

最佳答案

所有节点都指向同一个字符串,因此您想将函数 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 将修复它,但出于上述原因,您可能需要考虑编写自己的 strdup 副本 here

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

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

关于c - 为什么指针 "Start"会改变? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856935/

相关文章:

c++ - 提取 C/C++ 函数原型(prototype)

database - 写入文本文件或通过键/值数据库的速度

java - 如何以 MB(兆字节)为单位获取文件的大小?

version-control - VSS : Move file from one folder to another?

c++ - "Deep"头部依赖分析

c - 从结构体访问 TCP 标志

c - 从 C 中的文件行中提取信息

python - Python 中 2 个列表中字符串中的常见字符

javascript - 获取 javascript 函数实例本身以启用文档字符串。是否可以?

如果访问错误的字符串索引,c++ 不会抛出错误