我正在创建一个函数,它将一个单词列表转换成一个数组,供其他函数使用,但不知怎的,我正在重写前面的单词。我检查了记忆地址,它们看起来不一样,但当我重新检查一次,我完成了单词的输入,它们都是一样的。

static char **array;

//takes the name of a data file and reads it into an array
static void InitDictionary(char *fileName){
  //slide 36, chap 3
  FILE *file;
  int count,i;
  char dummy[30];
  file = fopen(fileName, "r");

  while( fscanf(file, "%s", dummy) == 1 ){//counting at first
    count++;
  }
  fclose(file);

  array = (char**) malloc(count * sizeof(char*) );
  count = 0;
  file = fopen(fileName, "r");
    while( fscanf(file, "%s", dummy) == 1 ){//now putting values in array
      char newEntry[30];
      strcpy(newEntry,dummy);
      array[count] = newEntry;
      printf("%d - %s : %p \n",count, array[count], &array[count]);

      count++;
    }
  fclose(file);

  for(i=0;i<count;i++)
    printf("%d - %s : %p\n",i, array[i], &array[count] );


}

谢谢

最佳答案

user470379是正确的,您没有为每个新词分配空间。一种可能的解决方法是更换三条线路:

char newEntry[30];
strcpy(newEntry,dummy);
array[count] = newEntry;

具有
array[count] = strdup(dummy);

10-04 21:38
查看更多