[英]Why am I limited to an arbitrary small ( array size when initializing an array with a const length in C?
Note: I have seen In C, why can't a const variable be used as an array size initializer? 注意:我已经在C中看到了,为什么不能将const变量用作数组大小的初始化程序? already, but this doesn't quite answer my question (or I am not understanding it fully). 已经,但这还不能完全回答我的问题(或者我没有完全理解它)。
This works: 这有效:
int main() {
const long COUNT = 1048106;
int nums[COUNT];
return 0;
}
This crashes: 这崩溃:
int main() {
const long COUNT = 1048106000;
int nums[COUNT];
return 0;
}
I have read that this is actually an inappropriate use of const
to begin with (since it means read-only, not evaluated at compile time). 我已经读过,这实际上是对const
的不当使用(因为这意味着只读,在编译时不进行评估)。
So I am happy to use #define
or whatnot instead, but still, it bothers me why this works for some lengths but not but not any higher. 因此,我很乐意使用#define
或诸如此类的东西,但是仍然令我感到困扰的是为什么它在一定长度下有效,但没有更高的效力。
Both your array declarations are in fact variable length array declarations. 您的两个数组声明实际上都是可变长度数组声明。 COUNT
is not a constant expression in C, despite being const
. 尽管是const
,但COUNT
在C中不是常量表达式。
But regardless, the bigger size simply exceeds your implementation's limits, overflowing the call stack where those locals are usually allocated. 但是无论如何,更大的大小只会超出实现的限制,从而使通常分配了这些本地资源的调用堆栈溢出。 Though I suspect this behavior will go away should you compile with optimizations. 尽管我怀疑这种行为在您进行优化时会消失。 A compiler can easily deduce that nums
isn't used in your snippet, and remove it entirely. 编译器可以轻松推断出代码段中未使用nums
,并将其完全删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.