0

I am trying to pass a 3x3 array by reference in C++. However when I do it I get the error error: cannot convert ‘double*’ to ‘double’ in initialization. I tried to follow the instructions given on this page. I have a for loop in there but I am not going to be using that until I can get the array to pass properly:

void transpose(double (&arr)[3][3] )
{
    for (int counti = 0; counti < 3; counti++) {
        for (int countj = 0; countj < 3; countj++) {

            double i_swap = &arr[0][0];

        }
    }
}   

int main()
{
    double myarray[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    transpose(myarray);
    return 0;
}
Community
  • 1
  • 1
thewire247
  • 695
  • 1
  • 6
  • 22

2 Answers2

1

& is a reference. You're trying to set a pointer to a double which you can't like that.

void transpose(double (&arr)[3][3] )
{
    for (int counti = 0; counti < 3; counti++) {
        for (int countj = 0; countj < 3; countj++) {

            double i_swap = arr[0][0];

        }
    }
}   

int main()
{
    double myarray[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
    transpose(myarray);
    return 0;
}

Compiled

deW1
  • 5,196
  • 10
  • 35
  • 52
0

seems fine, just the swapping part needed (you can ofc use std::swap from <algorithm>)

void swap(double& a, double& b)
{
   double temp = a;
   a = b;
   b = temp;
}

Pay attention to the for-bounds. final code:

for (int y=1; y<3; y++)
   for(int x=0; x<y; x++) {
      std::swap(mat[y][x], mat[x][y]);  // stl

      //swap(mat[y][x], mat[x][y]);     // calling your swap function

      //double temp = mat[y][x];        // no swap function
      //mat[y][x] = mat[x][y];
      //mat[x][y] = temp;
   }
Exceptyon
  • 1,570
  • 17
  • 22