c++ - 动态数组与 C++ 中的静态绑定(bind)数组有何不同?

标签 c++

我正在学习 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/

相关文章:

c++ - 位掩码函数

c++ - 在NCurses CDK Matrix中,单个细胞可以着色吗?

c++ - 当我尝试使用异常时,为什么我的代码在 Qt Creator 中使用 -fno-exceptions 进行编译?

c++ - CloseHandle 混淆 - 我必须在句柄的多个 "copies"上调用 CloseHandle 吗?

C++ 类定义分为两个 header ?

c++ - 为什么右值/常量引用有内存地址和大小?

c++ - 将简单网格加载到 OpenGL 时遇到问题

c++ - (C++)使用g++返回 “undefined reference to ` WinMain @ 1 6'”的Win32 API示例代码

c++ - 局部变量是在评估函数返回值之前还是之后销毁的?

c++ - 用 C++ 计算圆周率