【问题标题】:Issue in filling up dynamic array from keyboard input[C]从键盘输入填充动态数组的问题[C]
【发布时间】:2020-01-31 19:11:10
【问题描述】:

我已经在 c 中实现了我自己的动态数组数据结构,现在我正在寻找一种方法来填充它们而不会失去它们的动态性。

如果我写类似

char str[ANY_CONSTANT];
fgets(str, ANY_CONSTANT, stdin);

我可以传递给我的程序的元素数量是在编译时定义的,这正是我不希望发生的。

如果我写类似的东西

char str[ANY_CONSTANT];
scanf("%s", &str)

我也有同样的情况。是否有任何功能可用于从键盘输入数据而没有任何固定尺寸?提前致谢!

【问题讨论】:

  • 两个代码都无效。您正在传递一个指针数组。

标签: c scanf fgets dynamic-arrays keyboard-input


【解决方案1】:

你可以试试POSIX getline函数:

char *buf = NULL;
size_t buflen = 0;
ssize_t readlen = getline(&buf, &buflen, stdin);
/* buf points to the allocated buffer containing the input
   buflen specifies the allocated size of the buffer
   readlen specifies the number of bytes actually read */

getline 从控制台读取整行,根据需要重新分配缓冲区以存储整行。

【讨论】:

    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多