[英]Returning a pointer to a 2-D array from a function
In order to understand how pointer work I wrote this function which has to return a 3*3 matrix. 为了理解指针的工作方式,我编写了此函数,该函数必须返回3 * 3矩阵。
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;
这里
m
是一个3 * 3的数组return p;
it gives the error return value type does not match function type
. 它给出错误
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. 使用p我没有返回指向3 * 3矩阵的指针。这有什么问题,有人可以帮我解决这个问题。
int (*)[3]
and int**
are not the same type: int (*)[3]
和int**
不是同一类型:
int**
is a pointer to a pointer to int
int**
是指向int
的指针 int (*)[3]
is a pointer of an array of 3 int
. int (*)[3]
是3 int
数组的指针。 Even if int [3]
may decay to int*
, pointer on there different type are also different. 即使
int [3]
可能会衰减为int*
,但那里不同类型的指针也不同。
The correct syntax to return int (*)[3]
would be: 返回
int (*)[3]
的正确语法为:
int (*Matrix::getMatrix())[3];
or with typedef
: 或使用
typedef
:
using int3 = int[3];
int3* Matrix::getMatrix();
And as m
is int[3][3]
, you may even return reference ( int(&)[3][3]
): 由于
m
是int[3][3]
,您甚至可以返回引用( int(&)[3][3]
):
int (&Matrix::getMatrix())[3][3];
and with typedef: 和typedef:
using mat3 = int[3][3];
mat3& Matrix::getMatrix();
It would be more intuitive with std::array
or std::vector
使用
std::array
或std::vector
会更直观
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.