【发布时间】:2021-09-10 07:40:47
【问题描述】:
我创建了一个程序,该程序接受用户输入他们想要在二维数组中生成的行数和列数。然后程序获取该数组并仅反转行的顺序。一切似乎都很好,但是当我输入行数和列数时,如果这两个整数之间的差大于 1,代码就会中断。我是 C++ 的初学者,所以我不完全确定这里发生了什么。任何帮助表示赞赏!
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int r;
int rows;
int cols;
cout << "how many rows: ";
cin >> rows;
cout << "\n";
cout << "how many columns: ";
cin >> cols;
cout << "\n";
int** matr = new int* [rows];
for (int i = 0; i < rows; i++)
{
matr[i] = new int[cols];
}
for (int j = 0; j < rows; j++)
{
cout << "\n";
for (int i = 0; i < cols; i++)
{
r = rand() % 50 - rand() % 50;
matr[i][j] = r;
cout << matr[i][j] << " ";
}
}
cout << "\n\n";
int **ptr = &matr[rows*cols];
for (int j = rows-1; j > -1; j--)
{
cout << "\n";
for (int i = 0; i < cols; i++)
{
*ptr = &matr[i][j];
cout << **ptr << " ";
}
}
cout << "\n";
}
调试时,Visual Studio 向我显示一条错误消息,显示“读取访问冲突”。我不知道它在这里试图告诉我什么,但我认为问题在于该错误。
【问题讨论】:
-
你交换了
rows和cols。第一个维度应该迭代到rows,第二个维度应该迭代到cols。 -
您有时在索引时混淆了行/列。当
j用于rows和i用于cols时,matr[i][j]应为matr[j][i]。
标签: c++ for-loop pointers reverse