先决条件:数组基础
在 C/C++ 中,多维数组用简单的话作为数组的数组。多维数组中的数据以表格形式(按行主顺序)存储。下面是声明N 维数组的一般形式:
多维数组的语法:
data_type array_name[size1][size2]….[sizeN];
data_type: Type of data to be stored in the array.
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions
二维数组是一维数组的数组。
二维数组的语法:
data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.
下面是二维数组的示意图:
有关多维和二维数组的更多详细信息,请参阅 C++ 中的多维数组文章。
问题:给定一个二维数组,任务是使用 C++ 中的 new 为二维数组动态分配内存。
解决方案:以下二维数组声明为 3 行 4 列,其值如下:
1 2 3 4
5 6 7 8
9 10 11 12
注意:这里M是行数, N是列数。
方法 1:使用单指针——在这种方法中,分配大小为 M*N的内存块,然后使用指针算法访问内存块。以下是相同的程序:
C++
// C++ program to dynamically allocate
// the memory for 2D array in C++
// using new operator
#include
using namespace std;
// Driver Code
int main()
{
// Dimensions of the 2D array
int m = 3, n = 4, c = 0;
// Declare a memory block of
// size m*n
int* arr = new int[m * n];
// Traverse the 2D array
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Assign values to
// the memory block
*(arr + i * n + j) = ++c;
}
}
// Traverse the 2D array
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Print values of the
// memory block
cout << *(arr + i * n + j)
<< " ";
}
cout << endl;
}
//Delete the array created
delete[] arr;
return 0;
}
C++
// C++ program to dynamically allocate
// the memory for 3D array in C++
// using new operator
#include
using namespace std;
// Driver Code
int main()
{
// Dimensions of the array
int m = 3, n = 4, c = 0;
// Declare memory block of size M
int** a = new int*[m];
for (int i = 0; i < m; i++) {
// Declare a memory block
// of size n
a[i] = new int[n];
}
// Traverse the 2D array
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Assign values to the
// memory blocks created
a[i][j] = ++c;
}
}
// Traverse the 2D array
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Print the values of
// memory blocks created
cout << a[i][j] << " ";
}
cout << endl;
}
//Delete the array created
for(int i=0;i
1 2 3 4
5 6 7 8
9 10 11 12
方法2:使用指针数组:这里创建一个指针数组,然后指向每个内存块。下面是说明这个概念的图表:
以下是相同的程序:
C++
// C++ program to dynamically allocate
// the memory for 3D array in C++
// using new operator
#include
using namespace std;
// Driver Code
int main()
{
// Dimensions of the array
int m = 3, n = 4, c = 0;
// Declare memory block of size M
int** a = new int*[m];
for (int i = 0; i < m; i++) {
// Declare a memory block
// of size n
a[i] = new int[n];
}
// Traverse the 2D array
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Assign values to the
// memory blocks created
a[i][j] = ++c;
}
}
// Traverse the 2D array
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Print the values of
// memory blocks created
cout << a[i][j] << " ";
}
cout << endl;
}
//Delete the array created
for(int i=0;i
1 2 3 4
5 6 7 8
9 10 11 12