Array size at run time without dynamic allocation is allowed?(允许在没有动态分配的情况下运行时的数组大小?)
问题描述
我已经使用 C++ 几年了,今天我看到了一些代码,但这怎么可能是完全合法的?
I've been using C++ for a few years, and today I saw some code, but how can this be perfectly legal?
int main(int argc, char **argv)
{
size_t size;
cin >> size;
int array[size];
for(size_t i = 0; i < size; i++)
{
array[i] = i;
cout << i << endl;
}
return 0;
}
在GCC下编译.
如何在没有new或malloc的情况下在运行时确定大小?
How can the size be determined at run-time without new or malloc?
只是为了仔细检查,我在谷歌上搜索了一些和我的所有类似代码都声称会给出存储大小错误.
Just to double check, I've googled some and all similar codes to mine are claimed to give storage size error.
即使是 Deitel 的 C++ 如何编程 p.常见编程错误 4.5 下的 261 个状态:
Even Deitel's C++ How To Program p. 261 states under Common Programming Error 4.5:
只能使用常量来声明自动和静态数组的大小.
Only constants can be used to declare the size of automatic and static arrays.
启发我.
推荐答案
这在 C99 中有效.
This is valid in C99.
C99 标准支持堆栈上的可变大小数组.可能您的编译器也选择支持这种结构.
C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too.
请注意,这与 malloc 和 new 不同.gcc 分配堆栈上的数组,就像它在 int array[100] 中所做的一样,只需调整堆栈指针即可.没有进行堆分配.这很像 _alloca.
Note that this is different from malloc and new. gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap allocation is done. It's pretty much like _alloca.
这篇关于允许在没有动态分配的情况下运行时的数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:允许在没有动态分配的情况下运行时的数组大小
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
