1

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

如果我写类似

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

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

如果我写类似

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

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

4

1 回答 1

2

您可以尝试 POSIXgetline功能:

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-01-31T19:18:54.190 回答