Variable in C + + does array length

Source: Internet
Author: User
Tags array length

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.