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.

1
  • I believe, you should be returning a type int*, which would return the value of p (ie., address of m) instead of int**. Commented Dec 29, 2014 at 10:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

In the first line you are missing an asterix in int**.
auto Matrix::getMatrix() -> decltype(m) (plus something to make it a reference)
@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 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: I edited the answer for clarification of the difference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.