[英]c++ Function creates a 2-d array and returns a pointer to the 2-D array
[英]Returning a pointer to a 2-D array from a function
為了理解指針的工作方式,我編寫了此函數,該函數必須返回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;
}
這里m
是一個3 * 3的數組return p;
它給出錯誤return value type does not match function type
。
使用p我沒有返回指向3 * 3矩陣的指針。這有什么問題,有人可以幫我解決這個問題。
int (*)[3]
和int**
不是同一類型:
int**
是指向int
的指針 int (*)[3]
是3 int
數組的指針。 即使int [3]
可能會衰減為int*
,但那里不同類型的指針也不同。
返回int (*)[3]
的正確語法為:
int (*Matrix::getMatrix())[3];
或使用typedef
:
using int3 = int[3];
int3* Matrix::getMatrix();
由於m
是int[3][3]
,您甚至可以返回引用( int(&)[3][3]
):
int (&Matrix::getMatrix())[3][3];
和typedef:
using mat3 = int[3][3];
mat3& Matrix::getMatrix();
使用std::array
或std::vector
會更直觀
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.