C ++可以使用可变长度数组,因为我的后续程序工作正常 [英] Does C++ can have variable length array as my following program worked
问题描述
i was told that arrays cant work like this but this has worked for me even with declaring with variable sized array in codeblocks. how so?
我尝试过:
What I have tried:
<pre>#include <iostream>
using namespace std;
int main() {
int a;
cin>>a;
int arr[a];
for(int i=0;i<a;i++)
{
cin>>arr[i];
}
cout<<arr[2];
return 0;
}
推荐答案
这不是可变大小的数组,而是指定数组的大小,
That is not a variable size array, you are specifying the size of the array,
cin >> a;
int arr[a]; // Right here.
尝试做除此之外的任何东西,例如,
Try doing anything other than that, such as,
int arr[5];
cin >> a;
// Try adding this to the array now,
int arr[a]; // See what happens.
虽然,是的,这是动态大小的数组,但不是可变大小的数组。它们之间存在巨大差异,它们在许多方面都是有用的和有害的。至于存在可变大小的数组,这个概念甚至不存在于其他高级语言中,例如C#,Java。它们还有容器(List等),用于处理在运行时增长或缩小的集合。
如果你想要一个可变大小的数组,用C ++查找向量。向量是一个可变大小的数组,它由数组支持,但它的大小可以在运行时更改 - 数组的大小不能在运行时更改,仅在创建时指定。
vector - C ++ Reference [ ^ ]
Although, yes, that is a dynamically sized array, but not a variable size array. There is a huge difference in between both of them and, they are both useful and harmful in many ways. As for existence of variable-sized arrays, the concept does not even exist in other high-level languages, such as C#, Java. They also have containers (List, etc.) that take care of the collections that grow or shrink on run-time.
If you want a variable sized array, look for vectors in C++. A vector is a variable sized array, it is backed by an array but its size can change on the runtime — the size of your array cannot be changed on runtime, only specified at creation.
vector - C++ Reference[^]
您可能正在使用支持C ++的GNU编译器:
You are probably using the GNU compiler which supports them for C++:
ISO C99允许使用可变长度自动数组,作为扩展,GCC在C90模式和C ++中接受它们。
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++.
这篇关于C ++可以使用可变长度数组,因为我的后续程序工作正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!