Passing arrays

I have a 3x3 array which I create and fill in one of my functions within my program. This function, lets call it makeMatrix(), is called from the main function and I want to make use of the matrix which this function makes. How do I retrieve this matrix from where it's created? Here's what the code looks like:

1
2
3
4
5
6
7
8
9
10
11
int main(){
makeMatrix(string s);

// I want to access the matrix which I created, right here.
}

makeMatrix(string s){
// I create the 3x3 array here and within this function, it is clear that I have the matrix I want to use. My problem is getting access to this matrix from the main method.
}

you are passing a string to makeMatrix() for what purpose..... i assume you are populating the array and not creating an array ? Also why do you have two functions with the same name. should be accessMatrix().


to make it simple you have to understand pointers to get this done...


first you must learn how to just pass a simple variable between functions.



void duplicate (int& a, int& b, int& c)

is an example in the tutorial, if you pass your arrray using this method to both functions, it will work.
Last edited on
If you are doing this c-style, pass the array in by reference:
1
2
3
4
5
6
7
8
9
10
void makeMatrix(double NewMatrix[][3][3]) //the last two dimensions are constrained, 
{
	NewMatrix[i][j][k] = something;
}

void someFunc()
{
    double MyMatrix[3][3][3]; //Matrix must be of size [x][3][3]
    makeMatrix(MyMatrix); //Just pass in the name.
}




I tested this with the following code and it worked fine:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

void makeMatrix(double NewMatrix[][3][3]) //All dimensions but the first must be known.
{
    for (int i=0; i<3; ++i)
        for (int j=0; j<3; ++j)
            for (int k=0; k<3; ++k)
                NewMatrix[i][j][k] = k + j*3 + i*9;
}

int main()
{
    double MyMatrix[3][3][3]; //Define the matrix
    makeMatrix(MyMatrix); //pass just the name

    for (int i=0; i<3; ++i)
    {
        for (int j=0; j<3; ++j)
        {
            for (int k=0; k<3; ++k)
                cout << MyMatrix[i][j][k] << " ";
            cout << endl;
        }
        cout << endl;
    }

    return 0;
}


I found the answer here:
http://www.cplusplus.com/forum/general/11627/
Last edited on
Topic archived. No new replies allowed.