明确定义术语的含义很重要。不幸的是,静态和动态数组的含义似乎有多种定义。
Static variables 是使用static memory allocation 定义的变量。这是一个独立于 C/C++ 的通用概念。在 C/C++ 中,我们可以像这样创建具有全局、文件或局部范围的静态变量:
int x[10]; //static array with global scope
static int y[10]; //static array with file scope
foo() {
static int z[10]; //static array with local scope
Automatic variables 通常使用stack-based memory allocation 实现。可以像这样在 C/C++ 中创建一个自动数组:
foo() {
int w[10]; //automatic array
这些数组 x, y, z 和 w 的共同点是它们每个的大小都是固定的,并且在编译时定义。
理解自动数组和静态数组的区别很重要的一个原因是静态存储通常在目标文件的data section(或BSS section)中实现,编译器可以使用访问数组的绝对地址,这在基于堆栈的存储中是不可能的。
dynamic array 通常的含义不是可调整大小的,而是使用dynamic memory allocation 实现的,在运行时确定固定大小。在 C++ 中,这是使用 new operator 完成的。
foo() {
int *d = new int[n]; //dynamically allocated array with size n
但可以使用alloca 创建一个在运行时定义的具有固定大小的自动数组:
foo() {
int *s = (int*)alloca(n*sizeof(int))
对于真正的动态数组,应该使用 C++ 中的 std::vector 之类的东西(或 variable length array in C)。
OP 问题中的作业意味着什么?我认为很明显,想要的不是静态或自动数组,而是使用new 运算符使用动态内存分配或使用例如非固定大小数组的数组。 std::vector.