C ++ declares an array when the number of array elements is unknown.

Source: Internet
Author: User

C ++ declares an array when the number of array elements is unknown.

  The methods we have learned from the book are that defining an array requires the array name, type, and number of array elements. Generally, the number of elements must be specified. Otherwise, compilation fails.

1,

int a[];

 

2,

int n;int a[n];

The above two cases cannot be compiled.

Of course, the number of elements does not need to be defined, that is, the array is initialized and assigned a value during the declaration.

int a[] = {1,2,3,4}

This is acceptable.

  So how do we declare this array when I don't want to initialize and assign values and cannot determine the number of elements?

I believe many people have encountered this problem, and so have I. Today I finally found a solution to this problem-declaring an Array Using Dynamic declarations.

First, let's take a look at the definition of a one-dimensional array. The Code is as follows:

int n;int *a = new int[n];

Of course, the dynamic declaration of an array is actually to apply for a space of n * sizeof (int) size to the memory according to the value of n. After the array is used up, you need to release the space:

delete []a;

How can we declare a two-dimensional array through dynamic declaration? The Code is as follows:

Int ** a = new int * [m]; // declare a group of pointers pointing to each row for (int I = 0; I <m; I ++) a [I] = new int [n] // declare the pointer of each column of each row

Similarly, the memory space needs to be released after the array is used:

for(int i = 0; i<m;i++)    delete []a[i];delete []a;

 Note that in the dynamically declared two-dimensional array, a [k] is an int * type and a pointer, therefore, you can only use a [I] [j] Or * (a + I) + j) to access the corresponding elements, you cannot use a [I * n + j] for access.

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: 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.