【发布时间】:2017-11-05 20:33:00
【问题描述】:
我正在尝试将字典存储到一个名为 spellingList 的大数组中。 fgets() 循环似乎工作正常,但是当检查存储在 spellingList 中的内容时,它显示数组的每个元素都是 zygote(字典中的最后一个单词)。
给定一个名为 dictionary 的文件,其中包含一长串单词,格式如下:
字典
barbecue
barbecue's
barbecued
barbecues
barbecuing
barbed
.
.
.
zwieback's
zygote
zygote's
zygotes
代码
int i = 0;
int j;
char *pos;
/* Open Dictionary */
FILE *dic;
dic = fopen("dictionary", "r");
/* Malloc Storage Array */
char **spellingList;
spellingList = malloc (sizeof(char*) * 100000);
if (spellingList == NULL){ // if malloc fails
printf("%s\n", "Malloc failure");
exit(0);
}
/* load dictionary into array */
while (1){
if (fgets (word, 50, dic) != NULL){
if ((pos=strchr(word, '\n')) != NULL){ // replace ending '\n' with a '\0'
*pos = '\0';
}
printf("%d %s\n", i, word ); // looks as expected
spellingList[i] = word;
i++;
}
else {
break;
}
} fclose(dic); // close fd to dictionary
for (j =0; j < 100; j++){ // output
printf("%d %s\n", j, spellingList[j]);
}
输出
.
.
.
90 zygotes
91 zygotes
92 zygotes
93 zygotes
94 zygotes
95 zygotes
96 zygotes
97 zygotes
98 zygotes
99 zygotes
【问题讨论】:
-
我假设
word是一个数组?然后让spellinglist中的所有指针指向指向同一个数组。 -
您一遍又一遍地存储同一个指针 (
word)。 -
char **不是数组!指针不能是数组。
标签: c arrays initialization