Hey guys!

I have an encryption project for school and i have to randomly generate a 3x3 matrix.
I know how to assign the values to the 2d array but i am unsure how to return the array.
I know it is possible to return a vector of a vector but i am no where near learning vectors yet.
Here is my defective code:

int* matrixGenerator (int * matrix)
{
    srand (time(0));

    int matrix [3][3];

    int x = 0, y = 0;



    while (x < 3)
    {
        while (y < 3)
        {
            matrix [x][y] = rand() % 10000;
            ++y;
        }
        y = 0;
        ++x;
    }




    for (int l = 0; l < 3; l++) 
    {
        for (int a = 0; a < 3; a ++)
        {
            cout << matrix [l][a] << "   ";
        }
        cout << endl;

        ++x;
    }
    return matrix; 

}

The easiest way is not to return the matrix at all, but declare it in main() and pass it in as a parameter. This works becuse arrays are always passed by reference, never by value.

void matrixGenerato(int matrix[][3])
{

}


int main()
{
   int matrix[3][3];

   matrixGenerato(matrix);
}

I know this is for school, but a dedicated matrix object or vector of vectors would be much better in terms of usability and flexibility than a multidimensional array:

#include <iomanip>
#include <iostream>
#include <vector>

#include <cstdlib>
#include <ctime>

using namespace std;

typedef vector<int> Row;
typedef vector<Row> Matrix;

Matrix matrixGenerator(int m, int n, int lbound = 0, int ubound = 10000, bool reseed = true)
{
    if (reseed)
    {
        srand((unsigned)time(0));
    }

    Matrix result(m, Row(n));

    for (int x = 0; x < m; x++)
    {
        for (int y = 0; y < n; y++)
        {
            result[x][y] = lbound + rand() % ubound;
        }
    }

    return result;
}

int main()
{
    Matrix mat = matrixGenerator(3, 3);

    for (Matrix::const_iterator row = mat.begin(); row != mat.end(); ++row)
    {
        for (Row::const_iterator item = row->begin(); item != row->end(); ++item)
        {
            cout << right << setw(6) << *item << ',';
        }

        cout << endl;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.