How to specify an array in the C ++ function so that the size of the array is determined by the input value of the function.

Source: Internet
Author: User

How to specify an array in the C ++ function so that the size of the array is determined by the input value of the function.

Today, I debugged A C ++ program and defined a one-dimensional array in a function. The size of the array is determined by the input value of the function.

This is the case:

Int a [r + L-1];

Then, an error is reported!

The error is as follows:

So the question is, must the array size be specified for defining arrays in C ++?

The answer is no. When defining arrays in C ++, we do not have to specify the array size.

However, the array size must be specified to define an array in the Code Editor, because the syntax of this definition array is in the C language (that is, regular array), and the size must be determined.

In C ++, there are two ways to define an array without specifying the size:

1) Use Pointer:

Int * a = new int [r-l + 1];

2) Replace the array with the container vector:

Vector <int>;

A vector is equivalent to a dynamic array and does not need to be specified. In C ++, the regular array is a data structure with a fixed size. It is easy to overflow in some functions and cannot achieve the actual purpose. Therefore, vector is recommended in C ++.

About the usage of vector, You can see another blog Author: https://www.cnblogs.com/yoke/p/6080080.html

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: info-contact@alibabacloud.com 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.