问题描述
这是一个有效的C ++程序,不会在任何机器上崩溃吗?
#include< iostream>
using namespace std;
int main(无效){
int i;
cin> i;
double X [i];
X [i-1] = 1123;
cout<< X [i-1]<< endl;
返回0;
}
标准对于定义和初始化
长度
非常数?这是非法的吗?或者在C ++中合法吗?
谢谢,
--j
Is this a valid C++ program that will not crash on any machine?
#include <iostream>
using namespace std;
int main( void ) {
int i;
cin >i;
double X[i];
X[i-1] = 1123;
cout << X[i-1] << endl;
return 0;
}
What does the standard say about defining and initializing arrays of
length
non-const? Is it illegal? Or is that legal in C++?
Thanks,
--j
推荐答案
根据当前的C ++标准,数组的长度必须是
编译时常量。
许多编译器提供了一个扩展,程序员可以使用运行时值定义一个
数组。
如果你正在编写便携式代码,使用新或矢量或矢量。或malloc或相反。
-
Frederick Gotham
According to the current C++ Standard, the length of an array must be a
compile-time constant.
Many compilers provide an extension whereby the programmer can define an
array using a runtime value.
If you''re writing portable code, use "new" or "vector" or "malloc" instead.
--
Frederick Gotham
您是否在发布之前在一台机器上尝试过它?
Did you try it even on one machine before posting?
大多数编译器都会编译它没问题 - 如果它们不是标准C ++
模式,那就是。
-
Frederick Gotham
Most compilers will compile it no problem -- if they''re not in Standard C++
mode, that is.
--
Frederick Gotham
这篇关于定义和初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!