先决条件:数组基础
在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
2D数组是一维数组的数组。
2D数组的语法:
data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.
以下是2D阵列的示意图:
有关多维和2D数组的更多详细信息,请参阅C++中的多维数组文章。
问题:给定2D数组,任务是使用C++中的new为2D数组动态分配内存。
解决方案:以下3D行和4列声明具有以下值的2D数组:
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