1

In order to understand how pointer work I wrote this function which has to return a 3*3 matrix.

int** Matrix::getMatrix(){
    cout<<"The  matrix is: \n";
    int (*p)[3]=m;

    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
        cout<<m[i][j]<<"\t";
        }
        cout<<"\n";
    }
    return p;

}  

Here m is a 3*3 array.But at the line return p; it gives the error return value type does not match function type.

With p am I not returning a pointer to a 3*3 matrix.?What's wrong with this.Can someone please help me to correct this.

clarkson
  • 561
  • 2
  • 16
  • 32

1 Answers1

2

int (*)[3] and int** are not the same type:

  • int** is a pointer to a pointer to int
  • int (*)[3] is a pointer of an array of 3 int.

Even if int [3] may decay to int*, pointer on there different type are also different.

The correct syntax to return int (*)[3] would be:

int (*Matrix::getMatrix())[3];

or with typedef:

using int3 = int[3];

int3* Matrix::getMatrix();

And as m is int[3][3], you may even return reference (int(&)[3][3]):

int (&Matrix::getMatrix())[3][3];

and with typedef:

using mat3 = int[3][3];
mat3& Matrix::getMatrix();

It would be more intuitive with std::array or std::vector

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • In the first line you are missing an asterix in `int**`. – cmaster - reinstate monica Dec 29 '14 at 10:26
  • `auto Matrix::getMatrix() -> decltype(m)` (plus something to make it a reference) – M.M Dec 29 '14 at 10:33
  • @MattMcNabb: `decltype(m)&` is the way. Even in C++14 with `auto` ( `int(*)[3]`) or `decltype(auto)` (`int[3][3]` that you can't return) doesn't improve that. – Jarod42 Dec 29 '14 at 10:54
  • @Jarod42 What is the difference of `int (*)[3]` and `int**`.I don't know much about pointers.Still beginning to learn it. Also what is meant by `int (*Matrix::getMatrix())[3]; `.What does `*Matrix` mean?Pointer to a class? – clarkson Dec 29 '14 at 13:06
  • @clarkson: I edited the answer for clarification of the difference. – Jarod42 Dec 29 '14 at 13:22
  • @clarkson: `int(*f())[3]` is the (unintuitive) syntax to return pointer on array of 3 int. I would recommend to not use it. Prefer the syntax with `typedef` or appropriate structure (generic `std::array` or a dedicated class of your own). – Jarod42 Dec 29 '14 at 13:23