【发布时间】:2019-02-20 06:22:56
【问题描述】:
我需要创建广告 2d 动态数组,然后创建一个函数,该函数将接收 2d 动态数组,然后将其顺时针旋转 90 度并将其返回给 main。 但是我不确定为什么我没有得到任何输出?是因为错误的交换技术吗? 我认为索引交换如下:
I J-----------I J
0 0 0 1
0 1 1 1
0 2 2 1
我带来了:
for (int i = 0; i <row;i++)
for(int j = 0;j<col; j++)
{
Roti[i+j][row-i]=arr[i][j];
}
代码:
#include <iostream>
using namespace std;
void print2DArray(int **arr, int rows, int cols);
int **Rotate(int **arr, int row, int col)
{
int **Roti = new int *[row];
for (int i = 0; i <row;i++)
{
Roti[i] = new int [col];
}
for (int i = 0; i <row;i++)
for(int j = 0;j<col; j++)
{
Roti[i+j][row-i]=arr[i][j];
}
return Roti;
}
int main()
{
int *A[3];
for (int i = 0; i < 3; i++)
{
A[i] = new int[3];
for (int j = 0; j < 3; j++)
{
A[i][j] = rand() % 20;
}
}
cout << "The array is :\n";
print2DArray(A, 3, 3);
int **ptr;
ptr=Rotate(A,3,3);
cout<<"-----"<<endl;
print2DArray(ptr, 3, 3);
for (int i = 0; i < 3; i++)
{
delete[] A[i];
}
return 0;
}
void print2DArray(int **arr, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
}
【问题讨论】:
-
你试过先在纸上解决吗?如果不先这样做。我也推荐你learn how to debug your programs。在调试器中运行你的程序,看看它是否崩溃。如果是这样,那么调试器将在崩溃的位置停止,让您知道它发生的时间和地点,并让您检查变量以确保它们正常。如果没有崩溃,则逐行逐行检查代码,以确保您的纸上解决方案正确实施并执行您认为应该执行的操作。
-
顺便说一句,你有内存泄漏。另外请花一些时间阅读how to ask good questions 和this question checklist。然后尝试改进您的问题,例如通过告诉我们预期输出与实际输出,或者如果您遇到崩溃,请向我们提供有关该问题的详细信息。
标签: c++ arrays algorithm for-loop dynamic