The format of creating two-dimensional arrays dynamically with new in C + + is generally the case:
Type (*P) [N] = new TYPE [][n];
Where type is a kind, n is the number of columns in a two-dimensional array. In this format, the number of columns must be indicated, while the number of rows does not need to be specified. Here, the type of P is type*[n], which is a pointer to an array of N-column elements.
There is also a way to not specify the number of columns in an array:
int **p;
p = new INT*[10]; Note that int*[10] represents an array of pointers with 10 elements
for (int i = 0; I! = ten; ++i)
{
P[i] = new INT[5];
}
Here is a pointer to the pointer, which points to a pointer array containing 10 elements, and each element points to an array of 5 elements, thus constructing an array of 10 rows and 5 columns.
When the array is used, the code that frees the space is:
for (int i = 0; I! = 5; i++)
{
Delete[] p[i];
}
Delete[] p;
To deal with two-dimensional arrays, you can use a reduced-dimension or two-dimensional method.
The dimensionality reduction method uses an array to accept the two-dimensional array, the first address of the two-dimensional element &a[0][0] as a parameter, and the function is accepted by int *.
The two-dimensional method is directly accepted by a two-dimensional array, but the number of columns needs to be specified.
If you want to create a two-dimensional array [m][n].
The following is a way to dynamically create a two-dimensional array by dynamically creating a pointer array .
Version C:
double **data;
data = (double * *) malloc (m*sizeof (double *));
for (int j=0;j<m;j++)
{
DATA[J] = (double*) malloc (n*sizeof (double)); each pointer element of this pointer array points to an array.
}
for (int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
data[i][j]=i*n+j;//initialization of array elements
}
}
For (i=0;i<m;i++)
{
Free (data[i]); //Undo the array that the pointer element points to
}
Free (data);
C + + version:
Double **data;
data = new Double*[m]; Set line or direct double **data=new double*[m]; A pointer to an array of pointers.
for (int j=0;j<m;j++)
{
Data[j] = new Double[n]; Each pointer element of this pointer array points to an array.
}
for (int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
data[i][j]=i*n+j;//initialization of array elements
}
}
for (i=0;i<m;i++)
{
Delete[] data[i]; First undo the array pointed to by the pointer element
}
delete[] Data;
Dynamic creation and processing of two-dimensional arrays in C + +