为什么指针“开始”会改变? (C)

时间:2015-11-22 16:06:41

标签: 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->字指向列表中的第一个单词。然后,循环浏览文件中的其余单词,将它们存储到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;
}

2 个答案:

答案 0 :(得分:2)

所有节点都指向相同的字符串,因此您希望将函数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也可能失败,因此您必须添加一些错误检查。

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

答案 1 :(得分:0)

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

Current = Start = AllocateWords(currentWord);