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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.