基于控制台输入的 C 动态数组
我正在编写一个存储来自控制台的输入的程序。为了简化它,可以说我需要输出写入控制台的内容。
所以我有这样的想法:
int main()
{
char* input;
printf("Please write a bunch of stuff"); // More or less.
fgets() // Stores the input to the console in the input char*
printf(input);
}
或多或少就是这样。只是想给你一个总体思路。那么,如果他们输入 999999999999 大小的内容怎么办?如何动态分配 char* 为该大小。
I am writing a program that stores input from the console. To simplify it lets say I need to output what was wrote to the console.
So I have something like this:
int main()
{
char* input;
printf("Please write a bunch of stuff"); // More or less.
fgets() // Stores the input to the console in the input char*
printf(input);
}
So that is it in more or less. Just trying to give you the general idea. So what if they input something the size of 999999999999. How can I assign a char* to be that size dynamically.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这允许一个相当大的空间。您可以检查数据中是否确实有换行符。
如果这还不够,请研究 POSIX 2008 函数
getline()
,在 Linux 中可用,它根据需要动态分配内存。
That allows for a rather large space. You could check that you actually got a newline in the data.
If that's not sufficient, then investigate the POSIX 2008 function
getline()
, available in Linux, which dynamically allocates memory as necessary.这是一个示例 - 您需要验证输入并确保不会溢出缓冲区。在此示例中,我丢弃任何超过最大长度的内容并指示用户重试。另一种方法是在发生这种情况时分配一个新的(更大的)缓冲区。
fgets()
第二个参数是您将从输入中读取的最大字符数。实际上,我正在考虑此示例中的\n
并删除它,您可能不想这样做。Here's an example - you need to validate the input and make sure you don't overflow your buffer. In this example, I discard anything over the max length and instruct the user to try again. Another approach would be allocating a new (larger) buffer when that happened.
fgets()
second argument is the maximum number of characters you will read from the input. I'm actually accounting for the\n
in this example and getting rid of it, you may not want to do so.