简体   繁体   English

从函数返回指向二维数组的指针

[英]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] ): 由于mint[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::arraystd::vector会更直观

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM