我正在检查在C++中两个二维数组的行为,一个是从堆栈分配,另一个是从堆分配。
我创建了两个相同形状的二维数组,并将这些数组填充了一些数据。然后我尝试用两种不同的方法读取数组,第一种方法是使用简单的数组索引格式“Arr [ROW] [COLUMN]”。然后我使用指针解引用来读取数组,并且我得到了堆分配数组的两个不同结果,但对于堆栈分配数组,结果相同。我正在尝试理解为什么结果不同。如有任何澄清,我将不胜感激。提前谢谢。
我运行的代码如下:
#include <iostream>
using namespace std;
int main(){
int rows = 6;
int columns = 3;
// allocate from the stack.
double q[rows][columns];
// allocate from the heap.
double ** a;
a = new double*[rows];
for(int i = 0; i < rows; ++i){
a[i] = new double[columns];
}
// populate the arrays.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
a[i][j] = columns*i+j;
q[i][j] = columns*i+j;
}
}
cout << "*****************" << endl;
cout << "Array indexing method." << endl;
cout << "*****************" << endl;
// print the heap allocated array using array indexing.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << a[i][j] << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
// print the stack allocated array using array indexing.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << q[i][j] << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
cout << "Pointer dereferencing method." << endl;
cout << "*****************" << endl;
// print the heap allocated array.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << *(&a[0][0] + columns*i + j) << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
// print the stack allocated array.
for(int i = 0; i < rows; ++i){
for(int j = 0; j < columns; ++j){
cout << *(&q[0][0] + columns*i + j) << '\t';
}
cout << endl;
}
cout << "*****************" << endl;
// release the memory allocated to the heap.
for(int i = 0; i < rows; ++i){
delete[] a[i];
}
delete a;
return 0;
}
我获得的结果如下:
*****************
Array indexing method.
*****************
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
15 16 17
*****************
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
15 16 17
*****************
Pointer dereferencing method.
*****************
0 1 2
0 3 4
5 0 6
7 8 0
9 10 11
0 12 13
*****************
0 1 2
3 4 5
6 7 8
9 10 11
12 13 14
15 16 17
*****************
在第三个输出块中,我可以看到堆分配的数组没有被正确地读取,但是栈分配的数组被正确读取了。
再次感谢。
double q[rows][columns];
这是使用非标准的 C++ 变长数组(VLA)。 - user0042std::endl
额外的功能吗?'\n'
就可以换行。 - Pete Becker[ ][ ]
语法。 - PaulMcKenziedouble **
数组显示与您发布的(非标准)VLA版本相同,在此处查看。 - PaulMcKenziedouble **
。您的尝试以一种天真的方式分配数组——每行一个分配。 - PaulMcKenzie