【发布时间】:2013-11-22 04:56:16
【问题描述】:
我从给定文件(字典)中读取单词到单个字符串,并将字符串分配给字符串数组的第 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;
}
我将代码更改为此及其工作!我定义了全局变量“表”并删除了指针(也是动态分配函数)。我很好奇为什么指针不适用于此代码的 C 中的字符串数组(我知道方括号也表示“指针”)?因为我对整数数组没有不好的经验。抱歉英语不好,这是新代码:`
字符词[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);
}`
【问题讨论】:
-
当你把 C、字符串和一个没有经验的程序员扔在一个房间里时,我总是很惊讶会出错多少......
-
我刚刚稍微编辑了您的帖子,以修正正文和问题标题中的一些格式(例如,"C" 以大写形式书写)。