我正在编写一个程序,该程序应该通过在名为GetInput的函数中使用输入重定向来从文本文件获取输入。 (文本文件包含10个单词。)然后,该代码应能够在“打印”功能中打印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;
}

(注意:这是一项家庭作业。谢谢您,如果不清楚,抱歉)

最佳答案

由于*operator precedence,表达式*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;
}

上面的代码添加了一些安全检查,因此您不会超出所读入的临时数组或ListWords数组的范围。它还确保ListWords数组已初始化,因此,如果您读取的单词少于10个,则剩余的指针将为NULL

当然,您需要相应地更改main函数以及Print函数,因为现在它仅需要单个字符串作为参数,而不是字符串数组。当然,您还需要对数组中的每个字符串进行free编码,因为释放了数组。

关于c - 值未保留在函数外部,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35742580/

10-09 08:43