我试图将某些单词保存到一个指向数组的指针中 (**valid_words),但我遇到了一个我不明白的问题。下面是我尝试使用的函数,最终结果是根据 iline 和 dline 相等的条件,让 valid_words 包含所有有效词。
void CheckFile(char *input_file, char *dictionary_file, char *output_file, char **valid_words)
{
/* Open files as read or append */
FILE *input, *dictionary, *output;
input = fopen(input_file, "r");
dictionary = fopen(dictionary_file, "r");
output = fopen(output_file,"a");
int word_count = 0;
/* Read from files */
if (input != NULL && dictionary!= NULL)
{
char *iline = malloc(MAXSIZE*sizeof(char));
char *dline = malloc(MAXSIZE*sizeof(char));
while (fgets (iline, sizeof iline, input) != NULL)
{
while (fgets (dline, sizeof dline, dictionary) != NULL)
{
trimwhitespace(iline);
trimwhitespace(dline);
if (strcasecmp(iline, dline) == 0 )
{
fprintf(output, "%s\n",iline);
valid_words[word_count] = iline;
printf("Word Count: %d\n", word_count);
printf("At Zero: %s\n", valid_words[0]);
printf("Valid Word: %s\n", valid_words[word_count]);
printf("Actual Word: %s\n", iline);
word_count++;
}
}
rewind(dictionary);
}
fclose(input);
fclose(dictionary);
fclose(output);
free(iline);
free(dline);
}
else
{
printf("An error has occured\n");
}
}
我得到的当前输出是
Word Count: 0
At Zero: miles
Valid Word: miles
Actual Word: miles
Word Count: 1
At Zero: limes
Valid Word: limes
Actual Word: limes
Word Count: 2
At Zero: smile
Valid Word: smile
Actual Word: smile
Word Count: 3
At Zero: slime
Valid Word: slime
Actual Word: slime
我期待在零时:始终输出“英里”,但这并没有发生。 函数被调用后,打印 valid_words[i] 不会打印任何内容。 如果有人能帮助我,我将非常感激,并且愿意接受任何批评。您可以在此处找到完整的实现 http://pastebin.com/TjxLRVaC 谢谢。
最佳答案
为什么它不起作用的答案是 -
valid_words[word_count] = iline;
在确保 valid_words
中的元素最多可以容纳 MAXSIZE
个字符后,您应该使用 strcpy
或使用 strncat
(注意:不是 strncpy
),确保您插入的 valid_words
元素中的第一个(真正的第零个)字符是 '\0'
.
一些观察:
假设 MAXSIZE
是一个 #define
d 常量,这样更好 -
char iline[MAXSIZE];
char dline[MAXSIZE;
比起您拥有的 malloc 调用(顺便说一下,sizeof(char) 是一个定义。)
同样,您最好将 CheckFile
的最后一个参数更改为 char valid_words[][MAXSIZE]
(从而更改对 检查文件
).
希望这对您有所帮助。
关于c - 无法将字符串保存到指向数组的指针中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14248165/