我正在製作一個函數,將單詞列表轉換爲一個數組以供其他函數使用,但不知何故,我會覆蓋以前的單詞。我檢查內存地址',它們看起來不一樣,但是當我完成導入單詞後重新檢查時,它們都是一樣的。字符串覆蓋對方的數組?
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