值未在函数外保留

时间:2016-03-02 09:02:06

标签: c string function malloc

我正在编写一个程序,它应该通过在名为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;
}  

(注意:这是一个家庭作业。谢谢你,如果不清楚也很抱歉)

1 个答案:

答案 0 :(得分:5)

由于*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数组中的每个字符串,因为释放数组。