C ++与声明的大小初始化数组为整数的值 [英] c++ initialize array with declared size as a value of an integer
问题描述
我想用一个值我读入一个整数变量初始化与一个大小的数组。
我似乎无法理解为什么它的工作原理在开发-C ++而不是在Turbo C ++。这里的code,以帮助把事情说清楚。
I want to initialize an array with a size using a value I read into an integer variable. I cant seem to understand why it works in Dev-C++ but not in Turbo C++. Here's the code to help make things clear
int arr_size; //cin max value for lets say number of students or something...
cin >> arr_size;
int array[arr_size]; // declares array with size (assume 10 or 100) with range 0 to 9 or 0-99
编译器显示的Turbo C错误++(真的老了,我知道,但我的学校使用它不幸)。 DEV-C ++和$ C $个cblocks犯规。
The compiler shows an error in Turbo C++ (really old, I know, but my school uses it unfortunately). Dev-C++ and codeblocks doesnt.
为什么会这样?我知道它不好的做法有一个数组的大小相同为int值,因为他们中的一些书定义它,但有一个变通为此在Turbo C ++?
我想知道为什么错误发生,我怎么能得到解决它...非常感谢!
Why is that so? I know its bad practice "as they define it in some books" to have an array size the same as an int value, but is there a work around for this in Turbo C++? I want to know why the error happens and how I can get a work around it ... thanks a lot!
推荐答案
变长数组未在标准C ++允许。您可以在C99做到这一点。考虑使用C ++ 的std ::矢量为:
Variable length arrays are not allowed in standard c++. You can do it in C99. Consider using C++ std::vector as :
std::vector<int> array(arr_size);
和可以指数它的确切的像数组如果你不得不这样做。
And you can index it exactly like the array if you have to.
这篇关于C ++与声明的大小初始化数组为整数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!