我从给定的文件(字典)中读取单词并将字符串分配给字符串数组中的第n个索引。但它不起作用。 main()
中的for循环输出总是e3V\347
等,而createWordTable()
中的for循环输出总是字典的最后一个单词。以下是我的代码:
char** createWordTable();
char** createTable();
int main()
{
int i;
char **hashTable;
hashTable = createTable();
hashTable = createWordTable();
for (i=0; i< 338; i++) {
printf("%s \n",hashTable[i]);
}
return 0;
}
char** createWordTable(){
char word[20],**table;
FILE *dicFile;
table = createTable();
dicFile = fopen("smallDictionary.txt", "r");
if (dicFile == NULL) {
perror("error");
}
int wordCount = 0,endFile = 1;
while (endFile != EOF) {
endFile = fscanf(dicFile,"%s",word);
table[wordCount] = word;
wordCount = wordCount+1;
}
for (int i=0; i< 338; i++) {
printf("%s \n",table[i]);
}
return table;
}
char** createTable(){
char **table;
int i;
table = (char **)malloc(338 * sizeof(char *));
for (i=0; i<=338; i++) {
*table = (char *)malloc(25 * sizeof(char));
}
return table;
}
我将代码更改为以下内容,它可以正常工作!我定义了全局变量'table'并移除了指针(以及动态分配函数)。我非常好奇为什么在C语言中指针不能与字符串数组一起使用(我知道方括号也表示“指针”)?因为我没有用整数数组遇到过这种问题。抱歉我的英文不太好,以下是新代码:
char words[338][10];
int main()
{
createWordTable();
for (int i=0; i< 338; i++) {
printf("%s \n",words[i]);
}
return 0;
}
void createWordTable(){
char word[20];
FILE *dicFile;
dicFile = fopen("smallDictionary.txt", "r");
if (dicFile == NULL) {
perror("error");
}
int wordCount = 0;
while (!feof(dicFile)) {
fscanf(dicFile,"%s",word);
if(feof(dicFile)) break;
strcpy(words[wordCount], word);
wordCount = wordCount+1;
}
fclose(dicFile);
}`