我正在学习 C++,我刚刚阅读了有关动态数组的内容,以及它如何让您在运行时而不是编译时设置数组的长度。但是,您不需要动态数组来执行此操作。那么动态数组的意义何在?你什么时候用它?我觉得我错过了一些明显的东西,所以非常感谢任何见解。谢谢!
// Static binding.
int size = 0;
cout << "Enter size of array:" << endl;
cin >> size;
int array[size];
int array_length = sizeof(array) / sizeof(int);
cout << "Number of elements in array: " << array_length << endl;
// I just set the length of an array dynamically without using a dynamic array.
// So whats the point of a dynamic array then?
最佳答案
我不认为你可以在 C++ 中做到这一点。只有 C99 允许可变长度数组。
这甚至可以编译吗?您是在谈论 vector
类吗?
编辑:
它不会在 Visual Studio 2010 中编译:
1>..\main.c(207): error C2057: expected constant expression
1>..\main.c(207): error C2466: cannot allocate an array of constant size 0
1>..\main.c(207): error C2133: 'array' : unknown size
1>..\main.c(209): error C2070: 'int []': illegal sizeof operand
关于c++ - 动态数组与 C++ 中的静态绑定(bind)数组有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7451731/