Passing a pointer by reference

Hello,

I want to pass a pointer, of type double **x, by reference. I have tried two different option by passing **x and **&x, and both give same result for the test code I shown below. I was wondering which option is the correct. I am trying to implement the concept for my project.



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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
void myfun1 (double **x, int n)
{
 for (int i = 0;i<n;i++)
	 for(int j = 0;j<n;j++)
		 x[i][j] = i*j;
}

void myfun2 (double **&x, int n)
{
 for (int i = 0;i<n;i++)
	 for(int j = 0;j<n;j++)
		 x[i][j] = i*j;
}

int main ()
{
  int n = 5;
  double **y;

  // Allocating memory for y
  y = new double*[n];
  for( int i = 0 ; i < n ; i++ )
	  y[i] = new double [n];

  // test myfun1
  myfun1(y, n);
  // print y
  for(int i = 0;i<n;i++)
  {
	  for(int j = 0;j<n;j++)
	  {	
		  cout <<y[i][j]<<"\t ";
	  }cout<<"\n";
  }cout<<"\n";

   // test myfun2
  myfun2(y, n);
  // print y
  for(int i = 0;i<n;i++)
  {
	  for(int j = 0;j<n;j++)
	  {	
		  cout <<y[i][j]<<"\t ";
	  }cout<<"\n";
  }
  
  system("PAUSE");
  return 0;
}

Thanks
Last edited on
The results are the same because the expression x[i][j] accesses the same double whether x is the original pointer to pointer to double (pass-by-reference) or x is a copy of the original pointer to pointer to double (pass by value).

To experience a difference in behavior, try to assign a new value to x itself, from within the function (e.g. allocate a new array of pointers to arrays)

Also, don't forget to delete everything you new'd or use vectors to save yourself the headache (or a third-party matrix library, to make this even simpler)
There is no any sense to pass the pointer by reference because the pointer itself is not being changed.
Ok Thanks so much.
Topic archived. No new replies allowed.