问题描述
我已经教了自己的编程几年了,我确信如果你需要一个变量数组的声明,你需要使用 malloc 或<$ c今天我发现这是在g ++版本4.4.4下编译,没有警告或错误:
$ b$ b
#include< iostream>
using namespace std;
int main()
{
int size_array;
cin>> size_array;
int iTable [size_array];
for(int i = 0; i iTable [i] = i * i;
for(int i = 0; i< size_array; i ++)
cout< iTable [i]< endl;
return 0;
}
也可以编译完全正常,如果你使用gcc $ c> cout 和和 cin / code>)
在Visual Studio下,此代码无法编译,因为 size_array / p>
更改时?这是一个安全的方法?
这是一个C99功能 - - 它不是标准c ++的一部分。你可以使用它,如果你的编译器支持它,你不需要可移植性。如果编译器支持它,它是完全安全的使用 - 但它是一个坏习惯使用非标准的功能。
I have been teaching myself programming for couple of years, and I was sure that if you need array declaration of a variable number you need to use malloc or new.
Today I found that this compiles under g++ version 4.4.4, without warnings or errors:
#include <iostream> using namespace std; int main() { int size_array; cin >> size_array; int iTable[size_array]; for(int i=0;i < size_array;i++) iTable[i]=i*i; for(int i=0;i < size_array;i++) cout << iTable[i] << endl; return 0; }
Also it compiles completely fine if you are using gcc (after changing cout and cin with printf and scanf)
Under Visual Studio this code fails to compile since size_array is not constant.
When this was changed? This is a safe method?
This is a C99 feature - VLA - which is not a part of standard c++. You can use it if your compiler supports it and you don't require portability. If the compiler supports it, it's perfectly safe to use - but it's a bad habit using non-standard features.
这篇关于非const数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!