【发布时间】:2016-06-15 00:46:06
【问题描述】:
我正在编写一个程序,该程序应该通过在名为 GetInput 的函数中使用输入重定向从文本文件中获取其输入。 (文本文件包含 10 个单词。)然后代码应该能够在 Print 函数中打印 ListWord 的内容。
这是我目前所拥有的。
我在尝试运行此代码时不断出错。我试图在 ListWord 之前删除 * 并且代码有效,但它不保留存储在其中的单词(字符串)。但是在 ListWord 之前删除 * 对我来说没有意义。我究竟做错了什么?
void GetInput( char** ListWord)
{
int i=0;
char word[30]; //each word may contain 30 letters
*ListWord = malloc(sizeof(char*)*10); //there are 10 words that needs to be allocated
while(scanf("%s", word)==1) //Get Input from file redirection
{
*ListWord[i]= (char *)malloc(30+1);
printf("%s\n", word); //for checking
strcpy(*ListWord[i], word);
printf("%s\n", *ListWord[i]); //for checking
i++;
}
}
void Print(char *ListWord)
{
//print ListWord
int i;
for (i=0; i<10; i++)
{
printf("%s", ListWord[i]);
}
}
int main()
{
char * ListWord;
GetInput(&ListWord);
printf("%s\n", ListWord[0]);
Print(ListWord);
free(ListWord);
return 0;
}
(注意:这是一个家庭作业。谢谢,如果不清楚,请见谅)
【问题讨论】:
-
首先,
char * ListWord;实际上应该是char ** ListWord;,如果你想把它作为参数传递给函数(而不是从函数返回),参数类型应该是char ***。free会很复杂。 -
看起来你正在传递
by value而不是by reference -
@MisterMister 如果知道正好有 10 个单词,那你为什么不直接声明一个 10 个字符数组的二维数组呢?