为什么是C字符串不同,最大的char []的最大长度? [英] Why is max length of C string literal different from max char[]?

查看:201
本文介绍了为什么是C字符串不同,最大的char []的最大长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

澄清:既然一个字符串文字可以写成一个常量
的char []
(见下文),对文字实行较低的最大长度比
的char [] s是只是一个语法的不便。为什么C标准
鼓励这种?

Clarification: Given that a string literal can be rewritten as a const char[] (see below), imposing a lower max length on literals than on char[]s is just a syntactic inconvenience. Why does the C standard encourage this?

的C89标准对字符串字面翻译限制:

The C89 standard has a translation limit for string literals:

509个字符的字符串文字或宽字符串文字(并置后)

509 characters in a character string literal or wide string literal (after concatenation)

有没有一个字符数组的限制;也许

There isn't a limit for a char arrays; perhaps

32767字节的对象(在托管环境中只)

32767 bytes in an object (in a hosted environment only)

适用(我不知道是什么物体或托管环境的意思),但无论如何这是一个更高的极限。

applies (I'm not sure what object or hosted environment means), but at any rate it's a much higher limit.

我的理解是,一个字符串文字相当于包含字符字符数组,即:它总是可能重写这样的:

My understanding is that a string literal is equivalent to char array containing characters, ie: it's always possible to rewrite something like this:

const char* str = "foo";

这个

static const char __THE_LITERAL[] = { 'f', 'o', 'o', '\0' };
const char* str = __THE_LITERAL;

那么,为什么在这样的文字的硬性限制?

So why such a hard limit on literals?

推荐答案

在字符串文字的限制是一个编译时间要求;有在逻辑源极线的长度有类似的限制。编译器可能会使用一个固定大小的数据结构来保存源代码行和字符串。

The limit on string literals is a compile-time requirement; there's a similar limit on the length of a logical source line. A compiler might use a fixed-size data structure to hold source lines and string literals.

(C99增加了从509到4095个字符这些特定的限制。)

(C99 increases these particular limits from 509 to 4095 characters.)

在另一方面,对象(如字符数组)可以在运行时建造的。此限制由目标机器架构可能实行,而不是由编译器的设计。

On the other hand, an object (such as an array of char) can be built at run time. The limits are likely imposed by the target machine architecture, not by the design of the compiler.

请注意,这些是的的征收方案上界。一个编译器根本不需要施加任何限制有限。如果编译器强加线路长度的限制,它必须至少为509或4095个字符。 (大多数实际的编译器,我认为,不征收固定的限制;相反,它们动态分配内存)

Note that these are not upper bounds imposed on programs. A compiler is not required to impose any finite limits at all. If a compiler does impose a limit on line length, it must be at least 509 or 4095 characters. (Most actual compilers, I think, don't impose fixed limits; rather they allocate memory dynamically.)

这篇关于为什么是C字符串不同,最大的char []的最大长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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