Handing a 2D-Array to a function as reference

Hi there,

i'm trying to hand 2-dimensional-Array to a function as a C++-reference, so i can write to it and use the changed values in my main-function. But somehow it doesn't work yet...
Can anyone help? I'm having an exam tomorrow. :D
Thanks in advance for any try.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>
using namespace std;

void readMatrix (int &matrix);

int main()
{
	int matrix[10][10];
	
	readMatrix (matrix[10][10]);
}

void readMatrix (int& matrix)
{
	ifstream fin("file.txt");
	
	for (int i = 0; i < 10; i++)
		for (int j = 0; j < 10; j++)
			fin >> matrix[i][j]; // <- Error occures here.
	
	fin.close();
}
If you know the size of your array at compile time then you can do it like this.

1
2
3
4
void readMatrix( int matrix[][10] )
{
    /* Do stuff */
}


When you call it, you'd simply use:
 
readMatrix( matrix );


You don't really explicitly pass arrays by reference. They decay to pointers when passed about anyway.

If you didn't know the runtime size of your array, you could do this by using a pointer to a pointer parameter and passing in a dynamically sized array. As with all cases like this, I'll include the obligatory 'you're better off with vectors or std::arrays line'. So there it is. :-)
Last edited on
Thanks a lot, now i remember again!
Topic archived. No new replies allowed.