【问题标题】:Value was not retained outside of a function值未保留在函数之外
【发布时间】: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 个字符数组的二维数组呢?

标签: c string function malloc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    相关资源
    最近更新 更多