call by reference

Hi .
I want pass my array to function with reference , but I cannot pass array to a function . What is my mistake ?????


#include<iostream>
using namespace std;
void display( int& array[][2], int size );
int main ()
{

int a[2][2];
cout << " Please enter 4 number : " ;
for ( int i = 0 ; i < 2 ; i++ )
{
for ( int j = 0 ; j < 2 ; j++)
cin >> a[i][j];
}
display(a ,2);
return 0;

}
void display ( int& array[][2] , int size)
{
for ( int i=0 ; i < 2 ; i++)
{
for ( int j = 0 ; j < 2 ; j++)
cout << array[i][j];
}

}


void display ( int (& array)[][2] , int size)

***I don't see the point of passing an array by reference (&) ***
Last edited on
i changed my program but the compiler return the error
#include<iostream>
using namespace std;
void display ( int (& array)[][2] , int size);//call by reference
int main ()
{

int a[2][2];
cout << " Please enter 4 number : " ;
for ( int i = 0 ; i < 2 ; i++ )
{
for ( int j = 0 ; j < 2 ; j++)
cin >> a[i][j];
}
display(a ,2); //call function
return 0;

}
void display ( int (& array)[][2] , int size) //call by reference
{
for ( int i=0 ; i < 2 ; i++)
{
for ( int j = 0 ; j < 2 ; j++)
cout << array[i][j];
}

}
//////////////////////////////////////////////
C:\c++\array\array.cpp|3|error: parameter `array' includes reference to array of unknown bound `int[][2]'|
C:\c++\array\array.cpp||In function `int main()':|
C:\c++\array\array.cpp|14|error: invalid initialization of reference of type 'int (&)[][2]' from expression of type 'int[2][2]'|
C:\c++\array\array.cpp|3|error: in passing argument 1 of `void display(int (&)[][2], int)'|
C:\c++\array\array.cpp|19|error: parameter `array' includes reference to array of unknown bound `int[][2]'|
||=== Build finished: 4 errors, 0 warnings ===|

The point of passing an array by reference to the function is so that the array inside the function represents the array passed in as argument to the function itself, not a copy of it's value. That way, any operation on the array inside the function will affect the array passed in as argument.

Anyway, you must specify the size of the first dimension of the array. The variable size is unnecessary.

void display(int &array[2][2]);
please use code blocks in future, additionally for small sample apps like this if it's not a specific requirement to pass by reference, then you can simply declare your array as private class member which voids the need to pass by reference.
Last edited on
arrays aren't passed by value anyway. They're passed by pointer. You don't need to make a reference in this case.

1
2
3
4
// this prototype works just fine and does
//  not copy the array:

void display( int array[][2], int size );
Topic archived. No new replies allowed.