【发布时间】:2018-02-22 16:43:53
【问题描述】:
我正在检查 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];VLA 不是标准 c++。 -
这不是问题,但您真的需要
std::endl需要的额外内容吗?'\n'结束一行。 -
不,我不知道,这个例子你是对的
\n会很好。 -
这与在堆上分配与在堆栈上分配无关,顺便说一句。您可以在“堆”上分配一个连续的内存块。
-
是的,只是分配
arr = new double[rows * columns];会产生更好的结果。然后访问第 3 行,第 2 列,您可以这样做:arr[row * columns + col]
标签: c++ arrays memory-management