由非常量变量定义的大小数组 [英] Array of size defined by not constant variable
本文介绍了由非常量变量定义的大小数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有这样的代码:
#include <iostream>
int main()
{
int size;
std::cin >> size;
size = size + 1;
int tab3[size];
tab3[0] = 5;
std::cout << tab3[0] << " " << sizeof(tab3) << std::endl;
return 0;
}
结果是:
$ g++ prog.cpp -o prog -Wall -W
$ ./prog
5
5 24
为什么这段代码甚至可以编译?数组的长度不应该是一个常量变量吗?
Why does this code even compile? Shouldn't be length of array a constant variable?
我使用的是 g++ 4.4.5 版.
I used g++ version 4.4.5.
推荐答案
C++ 中的可变长度数组可用作 GCC 中的扩展.编译所有警告应该会提醒您注意这一事实(包括 -pedantic
).
Variable-length arrays in C++ are available as an extension in GCC. Compiling with all warnings should have alerted you to that fact (include -pedantic
).
这篇关于由非常量变量定义的大小数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文