C 结构有大小限制吗?
C 结构有大小限制吗?
Are there any size limitations for C structures?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
C 结构有大小限制吗?
Are there any size limitations for C structures?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
从C标准来看:
除此之外,上限为
SIZE_MAX
(size_t
的最大值)。From the C standard:
Other than that, the upper bound is
SIZE_MAX
(maximum value forsize_t
).由于
sizeof
运算符生成size_t
类型的结果,因此限制应为SIZE_MAX
。您可以像这样确定
SIZE_MAX
的值:这是编译器应该允许的。运行时环境允许什么是另一个故事。
实际上,在堆栈上(本地)声明类似大小的对象是行不通的,因为堆栈可能比
SIZE_MAX
小得多。全局拥有这样的对象可能会使可执行加载程序在程序启动时抱怨。
Since the
sizeof
operator yields a result of typesize_t
, the limit should beSIZE_MAX
.You can determine the value of
SIZE_MAX
like this:This is what the compiler should allow. What the runtime environment allows is another story.
Declaring a similarly sized object on the stack (locally) in practice will not work since the stack is probably much, much smaller than
SIZE_MAX
.Having such an object globally might make the executable loader complain at program startup.
经验分析
在实践中,像 GCC 这样的实现似乎只允许小于
size_t
的结构,可能受PTRDIFF_MAX
的约束。另请参阅:最大大小是多少C 中的数组?使用:
我们编写程序:
然后在 Ubunbu 17.10 中:
可以运行。但是,如果我们取消注释
S31
,则会失败:因此最大大小介于 2^30 和 (2^31 - 1) 之间。
然后我们可以将
S30
转换为:并由此确定在此实现上的最大大小实际上是
2^31 - 1 == PTRDIFF_MAX
。Empirical analysis
In practice, implentations like GCC seem to only allow structs smaller than
size_t
, perhaps bound byPTRDIFF_MAX
. See also: What is the maximum size of an array in C?Using:
We make the program:
and then in Ubunbu 17.10:
works. But if we uncomment
S31
, it fails with:So the maximum size is between 2^30 and (2^31 - 1).
Then we can convert
S30
to:and with that we determine that the maximum size is actually
2^31 - 1 == PTRDIFF_MAX
on this implementation.