It's important to have clear definitions of what terms mean. Unfortunately there appears to be multiple definitions of what static and dynamic arrays mean.
Static variables are variables defined using static memory allocation. This is a general concept independent of C/C++. In C/C++ we can create static variables with global, file, or local scope like this:
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 are usually implemented using stack-based memory allocation. An automatic array can be created in C/C++ like this:
foo() {
int w[10]; //automatic array
What these arrays , x, y, z
, and w
have in common is that the size for each of them is fixed and is defined at compile time.
One of the reasons that it's important to understand the distinction between an automatic array and a static array is that static storage is usually implemented in the data section (or BSS section) of an object file and the compiler can use absolute addresses to access the arrays which is impossible with stack-based storage.
What's usually meant by a dynamic array is not one that is resizeable but one implemented using dynamic memory allocation with a fixed size determined at run-time. In C++ this is done using the new
operator.
foo() {
int *d = new int[n]; //dynamically allocated array with size n
But it's possible to create an automatic array with a fixes size defined at runtime using alloca
:
foo() {
int *s = (int*)alloca(n*sizeof(int))
For a true dynamic array one should use something like std::vector
in C++ (or a variable length array in C).
What was meant for the assignment in the OP's question? I think it's clear that what was wanted was not a static or automatic array but one that either used dynamic memory allocation using the new
operator or a non-fixed sized array using e.g. std::vector
.