Variable-length one-dimensional arrays
The variable-length array here refers to an array that cannot determine the length of the array at compile time, and the program needs to dynamically allocate memory space at run time. The simplest way to implement a variable-length array is to change the length of a one-dimensional array, which you can do:
File name: array01.cpp #include <iostream> using namespace std; int Main () { int len; cin>>len; Use pointer p to point to new dynamically allocated memory space of len*sizeof (int) *p=new Int[len]; ........... Delete[] p; return 0; }
Note int *p=new Int[len];
This sentence, you cannot do this:
int P[len];
The C + + compiler will complain that Len's size cannot be determined, because the array is declared in this form, and the size of the array needs to be determined at compile time. And that's not true:
int p[]=new Int[len];
The compiler will say the int* type can not be converted to int[] type, because a memory space opened with new will return the first address of the memory, so to assign this address to a pointer, so to use an int *p=new Int[len];
Array01.cpp implements a variable-length one-dimensional array, but to develop a good habit is to note that you want to unregister the pointer p so that the program frees up the memory space opened with new.
New assignment of dynamic arrays in C + +