我正在制作一个函数,将单词列表转换为一个数组以供其他函数使用,但不知何故,我会覆盖以前的单词。我检查内存地址',它们看起来不一样,但是当我完成导入单词后重新检查时,它们都是一样的。字符串覆盖对方的数组?
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]);
}
感谢
完成后一定要记得释放内存 - 为您必须释放新副本的strdup mallocs空间。 – user470379 2010-10-19 21:28:38
@ user470379 - 确切地说,单独执行strdup是很多繁琐的资源管理。将整个文件读入单个分配的内存块然后索引和NUL终止每个单词可能会更简单快捷。然后,整个事情可以在稍后被释放。 – Blastfurnace 2010-10-19 21:44:24