I'm trying to fill an array with random numbers using pointers. Here's my code so far:
#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;
}
}
When I print the matrix using the fillMatrix
function I get the following
17 24 11 0 20
13 3 0 13 22
20 21 11 19 18
After printing out the matrix_ptr_ptr
in main by using the for loop in main I get:
17 13 20 21 11
13 20 21 11 19
20 21 11 19 18
How can I get matrix_ptr_ptr
in main to equal the matrix outputted by the fillMatrix
function? Any help would be appreciated