Mis*_*ter 2 c string malloc function
我正在编写一个程序,它应该通过在一个名为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;
}  
Run Code Online (Sandbox Code Playgroud)
(注意:这是一个功课.谢谢你,如果不清楚的话,对不起)
由于*运算符优先级,表达式*ListWord[i]不会按照您的想法执行.实际上,您应该从您拥有的代码中获得错误或警告.
编译器认为这*ListWord[i]意味着*(ListWord[i]),这是不正确的.你需要使用(*ListWord)[i].
不幸的是,这只是你问题的开始.更大的问题是,传递给函数GetInput的指针不是指向可能成为字符串数组的指针,而是指向单个字符串的指针.
对于动态分配的字符串数组,您需要一个指向开头的指针,然后在其上模拟传递引用,即您需要成为一个三星程序员,这是您应该避免的.
而不是尝试传入要分配为参数的数组,而是GetInput 返回数组.就像是
char **GetInput(void)
{
    // Allocate ten pointers to char, each initialized to NULL
    char **ListWords = calloc(10, sizeof(char *));
    if (ListWords == NULL)
        return NULL;
    char word[31];
    for (int i = 0; i < 10 && scanf("%30s", word) == 1; ++i)
    {
        ListWords[i] = strdup(word);
    }
    return ListWords;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码添加了一些安全检查,因此您不会超出您读入的临时数组或ListWords数组的范围.它还确保ListWords数组已初始化,因此如果您读取的字数少于10个,则剩余的指针将为NULL.
当然,您需要相应地更改main函数,还需要更改Print函数,因为现在它只需要一个字符串作为参数,而不是字符串数组.您当然也需要free数组中的每个字符串,因为释放数组.