In Java, this is perfectly possible, for example, we run the following program:
Package Cn.darrenchan.storm; Import java.util.Arrays; Public class Test { publicstaticvoid main (string[] args) { int num = 5; int New int [num]; System.out.println (arrays.tostring (array));} }
The output is: [0, 0, 0, 0, 0]
In C + +, however, variables are not supported in C + + as array length parameters, such as int num=10;int array[num];
Writing this will prompt the compilation error " expression must contain constant value ". C + + Primer This book is also true, the use of VS programming will also report errors, but with codeblocks will not, and the results are correct, still do not understand why.
But what if I want to achieve a similar effect?
The variable assignment of the length of the moving array can be dynamically requested by a pointer, as follows:
int Ten ; *newint[num];
The array can be used as an array, the length of which can be computed from the time the program is run. If it is a normal array such as int is[10] Compile must be able to determine the length of the array, or will be reported compile errors, so flexibility is more limited. I think this is one of the reasons for the existence of new, the allocation of memory in the stack, the size is determined at compile time, if you want to dynamically calculate the size of the use of memory at runtime, it is necessary to use the new dynamic allocation function, to achieve higher flexibility.
Note: After C + + allocates space with new, remember that delete frees the memory when not in use, or there is a memory leak problem.
Variable in C + + does array length