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.