【问题标题】:Getting input from the command line?从命令行获取输入?
【发布时间】:2016-04-30 16:57:57
【问题描述】:

我想将 5 个书名中的每一个存储在数组中并打印出来。但是我在这里做错了什么? 输出将最后一个条目打印 5 次。

#include <stdio.h>

int main(int argc, const char * argv[])
{
    char * books[5];
    char currentBook[1024];
    for(int i = 0; i < 5; i++)
    {
        printf("Enter book:\n");
        gets(currentBook);
        books[i] = currentBook;
    }

    for(int i = 0; i <5; i ++)
    {
        printf("Book #%d: %s\n", i, books[i]);
    }
}

【问题讨论】:

  • 永远不要使用gets。它本质上是不安全的。
  • 您将currentBook 的地址存储在每个数组元素中,其中包含最新条目。我建议books[i] = strdup(currentBook);,然后你必须free数组中的每个指针,因为strdupmalloc获取内存。

标签: c loops pointers unix char


【解决方案1】:

鉴于你的声明

char * books[5];
char currentBook[1024];

,这段代码……

books[i] = currentBook;

... 将books[i] 指定为指向数组currentBook 开头的指针。您对各种i 多次执行此操作,导致指针数组都指向同一个数组。当您稍后打印每个指向的字符串时,它当然是相同的字符串。

您可以通过使用strdup() 来制作输入缓冲区的副本来解决此问题,而不是将books 的每个元素分配为指向同一事物。

【讨论】:

    【解决方案2】:

    问题是,你的指针将指向同一个字符串currentbook。 使用 strdup() 来复制字符串:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, const char * argv[])
    {
        char *books[5];
        char currentBook[1024];
        for (int i = 0; i < 5; i++)
        {
            printf("Enter book:\n");
            fgets(currentBook, sizeof(currentBook), stdin);
            books[i] = strdup(currentBook);
        }
    
        for (int i = 0; i < 5; i++)
        {
            printf("Book #%d: %s\n", i, books[i]);
            free(books[i]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      我想将 5 个书名中的每一个都存储在数组中

      那么你需要定义一个合适的数组。

      假设您要存储 5 个名称,每个名称的最大长度为 42 个字符,您需要定义一个由 5 个元素组成的数组,每个元素是一个 42 + 1 个字符的数组。

      就是这样定义chars 的二维数组

      char books [5][42 + 1]; /* Define one more char then you need to store the 
                                 `0`-terminator char ending each C "string". */
      

      并像这样使用它

      for(int i = 0; i < 5; i++)
      {
        printf("Enter book:\n");
        fgets(books[i], 42 + 1, stdin);
      }
      

      关于为什么使用gets()你可能想在这里阅读:Why is the gets function so dangerous that it should not be used?


      更多关于0-终止字符串的概念在这里:https://en.wikipedia.org/wiki/Null-terminated_string

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 1970-01-01
        • 2011-05-21
        • 1970-01-01
        • 1970-01-01
        • 2021-08-01
        • 2018-07-08
        相关资源
        最近更新 更多