一个字符数组中可以有多少个字符? [英] How many chars can be in a char array?

查看:52
本文介绍了一个字符数组中可以有多少个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#define HUGE_NUMBER ???

char string[HUGE_NUMBER];
do_something_with_the_string(string);

我想知道在不冒任何潜在内存问题、缓冲区溢出等风险的情况下,我可以添加到字符数组的最大数量是多少.我想让用户输入进去,而且可能是尽可能多的.

I was wondering what would be the maximum number that I could add to a char array without risking any potential memory problems, buffer overflows or the like. I wanted to get user input into it, and possibly the maximum possible.

推荐答案

请参阅 Jack Klein 的此回复(请参阅 原帖):

See this response by Jack Klein (see original post):

原始 C 标准(ANSI 1989/ISO1990) 要求编译器成功翻译至少一个程序至少包含一个一组环境示例限制.这些限制之一是能够创建至少一个对象32,767 字节.

The original C standard (ANSI 1989/ISO 1990) required that a compiler successfully translate at least one program containing at least one example of a set of environmental limits. One of those limits was being able to create an object of at least 32,767 bytes.

这个最低限度是在1999 年更新到 C 标准至少 65,535 个字节.

This minimum limit was raised in the 1999 update to the C standard to be at least 65,535 bytes.

不需要 C 实现提供比那个更大的对象大小,这意味着他们不需要允许更大的整数数组比 (int)(65535/sizeof(int)).

No C implementation is required to provide for objects greater than that size, which means that they don't need to allow for an array of ints greater than (int)(65535 / sizeof(int)).

用非常实际的术语来说,在现代电脑,不能说预先确定一个数组可以有多大创建.它可以取决于诸如物理内存量安装在电脑上,金额操作系统提供的虚拟内存,其他任务、驱动程序的数量,和已经运行的程序以及如何正在使用的大量内存.所以你的程序可能能够使用更多或今天运行的内存比它少可以使用昨天或它将能够明天用.

In very practical terms, on modern computers, it is not possible to say in advance how large an array can be created. It can depend on things like the amount of physical memory installed in the computer, the amount of virtual memory provided by the OS, the number of other tasks, drivers, and programs already running and how much memory that are using. So your program may be able to use more or less memory running today than it could use yesterday or it will be able to use tomorrow.

许多平台将他们最严格的对自动对象的限制,即在函数内部定义的那些不使用静态"关键词.在某些平台上,您可以如果它们是,则创建更大的数组静态或动态分配.

Many platforms place their strictest limits on automatic objects, that is those defined inside of a function without the use of the 'static' keyword. On some platforms you can create larger arrays if they are static or by dynamic allocation.

现在,为了提供稍微量身定制的答案,不要声明大型数组以避免缓冲区溢出.这接近在 C 中可以想到的最糟糕的做法.相反,花一些时间编写好的代码,并仔细确保不会发生缓冲区溢出.另外,如果您事先不知道数组的大小,请查看 malloc,它可能会派上用场 :P

Now, to provide a slightly more tailored answer, DO NOT DECLARE HUGE ARRAYS TO AVOID BUFFER OVERFLOWS. That's close to the worst practice one can think of in C. Rather, spend some time writing good code, and carefully make sure that no buffer overflow will occur. Also, if you do not know the size of your array in advance, look at malloc, it might come in handy :P

这篇关于一个字符数组中可以有多少个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆