尝试使用函数填充2维数组
Trying to fill a 2 dimensional array with random numbers using a function
我正在尝试使用指针填充一个随机数。到目前为止,这是我的代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
const int mRows = 3;
const int mCols = 5;
void fillMatrix(int ** m_ptr_ptr, int, int);
int main()
{
unsigned seed;
seed = time(0);
srand(47);
int matrix[mRows][mCols];
int* matrix_ptr[mRows];
int** matrix_ptr_ptr = &matrix_ptr[0];
for (int i = 0; i < mRows; i++)
{
matrix_ptr[i] = &matrix[i][0];
}
fillMatrix(matrix_ptr_ptr, mRows, mCols);
cout << endl << endl;
for (int j = 0; j < mRows; j++)
{
for (int k = 0; k < mCols; k++)
{
cout << setw(9) << *((*matrix_ptr_ptr + j) + k) << setw(6);
}
cout << endl << endl;
}
}
void fillMatrix(int **matrix_ptr_ptr, int N, int P)
{
for (int j = 0; j < N; j++)
{
cout << left;
for (int k = 0; k < P; k++)
{
*((*matrix_ptr_ptr + j) + k) = rand() % 25;
cout << setw(9) << *((*matrix_ptr_ptr + j) + k) << setw(6);
}
cout << endl << endl;
}
}
使用fillMatrix
函数打印矩阵时,我会得到以下
17 24 11 0 20
13 3 0 13 22
20 21 11 19 18
通过在Main中使用For Loop在MAIN中打印出matrix_ptr_ptr
后:
17 13 20 21 11
13 20 21 11 19
20 21 11 19 18
如何获得 matrix_ptr_ptr
的主体以等于fillMatrix
函数输出的矩阵?任何帮助将不胜感激
*((*matrix_ptr_ptr + j) + k) = rand() % 25;
看起来您需要做到这一点:
*(*(matrix_ptr_ptr + j) + k) = rand() % 25;
但更好(在评论中指出!)
matrix_ptr[j][k]
应用偏移后应取消。但是,如评论中指出的那样,请不要自己写矩阵的东西,请使用库。他们可以做到更有效,更好。它也更快地编程。
特征,大火或其他人应该满足您的需求。
相关文章: